Python自身的logger支持格式化输出,但没有颜色区分,也只能接收字符串参数。为了增加这些功能并方便拓展,自己写了一个logger模块。
源码
# logger.py
import sys
import datetime
_COLOR_CODE = {
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'purple': 35,
'cyan': 36,
'gray': 37,
}
class LOG_LEVEL(object):
DEBUG = 1
INFO = 2
WARN = 3
WARNING = 3
ERROR = 4
class Logger():
'''
日志输出类
支持多个非字符串参数自动格式化
支持前缀定制
支持ANSI颜色
'''
info = None
debug = None
warning = None
error = None
def __init__(self,
name=__name__,
level=LOG_LEVEL.DEBUG,
format='[{time}][{levelname}] - {message}',
datefmt='%Y-%m-%d %H:%M:%S',
colored = True
):
self._name = name
self._level = level
self._format = format
self._datefmt = datefmt
self._colored = colored
if self._colored:
self._format = self._format_coloring()
def set_config(self,
name=__name__,
level=LOG_LEVEL.DEBUG,
format='[{time}][{levelname}] - {message}',
datefmt='%Y-%m-%d %H:%M:%S',
colored=True
):
self._name = name
self._level = level
self._format = format
self._datefmt = datefmt
self._colored = colored
if self._colored:
self._format = self._format_coloring()
def _format_coloring(self):
parts = self._format.partition('{message}')
parts_colored = [self._color_format(part) if part != '{message}' else '{message}'
for part in parts
if len(part.strip()) > 0]
return ''.join(parts_colored)
def _color_format(self, text):
return '\x1b[{{color}}m{text}\x1b[0m'.format(color='color', text=text)
def _log_func_create(level, level_name, color):
def log_func(self, *args):
if self._level > level:
return
out = ''
for arg in args:
out += str(arg) + ' '
out_full = self._format.format(
time=datetime.datetime.now().strftime(self._datefmt),
levelname=level_name,
message=out,
name=self._name,
color=color
)
sys.stdout.write(out_full + '\n')
return log_func
setattr(Logger, 'debug', _log_func_create(LOG_LEVEL.DEBUG, 'DEBUG', _COLOR_CODE['cyan']))
setattr(Logger, 'info', _log_func_create(LOG_LEVEL.INFO, 'INFO', _COLOR_CODE['green']))
setattr(Logger, 'warning', _log_func_create(LOG_LEVEL.WARN, 'WARN', _COLOR_CODE['yellow']))
setattr(Logger, 'error', _log_func_create(LOG_LEVEL.ERROR, 'ERRO', _COLOR_CODE['red']))
logger = Logger()
使用
# main.py
from logger import logger, LOG_LEVEL
logger.set_config(
level = LOG_LEVEL.INFO # 设置最低打印等级为INFO
)
# other.py
from logger import logger
logger.debug('输出debug', [], {}) # 由于设置,不会打印出来
logger.info('输出info', [], {})
logger.warning('输出warning', [], {})
logger.error('输出error', [], {})
网友评论