让我们简化一下。我的目标是使用Python中的日志记录模块在终端中输出颜色。我希望信息有一个绿色前缀,警告有黄色前缀,错误有红色前缀。为了简单起见,让我们使用***作为前缀。
*** log text
*** another message with another prefix color我至今所做的一切
# declaration of function (global scope)
log = None
warn = None
error = None
def build_log_funcs():
# why I initialize it inside the function ?
# because script doesnt have to know about logging method
# the function just provide log functions
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
sh = logging.StreamHandler()
# LOG_FORMAT just global variable with pattern including %(levelmarks)s
# it will be replaced with ** with proper color
formatter = logging.Formatter(LOG_FORMAT)
sh.setFormatter(formatter)
logger.addHandler(sh)
def make_log_func(func, color, is_exit = False):
color_string = "\x1b[{};1m***\x1b[0m".format(color)
def newfunc(*args, **kwargs):
func(*args, extra={'levelmarks':color_string}, **kwargs)
if is_exit:
sys.exit(-1)
return newfunc
# 32, 33, 31 are color codes
log = make_log_func(logger.info, 32)
warn = make_log_func(logger.warning, 33)
error = make_log_func(logger.error, 31, is_exit = True)
return log, warn, error并把它当作
log, warn, error = build_log_funcs()它很管用,但我不喜欢的是:(从小到大的问题)
logging模块的功能。例如,启用/禁用调试消息为什么我不做简单的日志,警告,简单的函数?我不知道。logging是一个非常全面的模块,所以我将来可能需要它的特性。
我的问题是你怎么解决这个问题?也许有一个简单的显而易见的方式,我不知道。
发布于 2013-12-20 16:06:44
感谢Dominic的这链接。我看到了,但没有注意答案。下面的代码或多或少适合我
def setup_logger(logger):
logger.setLevel(logging.DEBUG)
sh = logging.StreamHandler()
formatter = logging.Formatter(LOG_FORMAT)
sh.setFormatter(formatter)
def decorate_emit(fn):
# add methods we need to the class
def new(*args):
levelno = args[0].levelno
if(levelno >= logging.CRITICAL):
color = '\x1b[31;1m'
elif(levelno >= logging.ERROR):
color = '\x1b[31;1m'
elif(levelno >= logging.WARNING):
color = '\x1b[33;1m'
elif(levelno >= logging.INFO):
color = '\x1b[32;1m'
elif(levelno >= logging.DEBUG):
color = '\x1b[35;1m'
else:
color = '\x1b[0m'
# add colored *** in the beginning of the message
args[0].msg = "{0}***\x1b[0m {1}".format(color, args[0].msg)
# new feature i like: bolder each args of message
args[0].args = tuple('\x1b[1m' + arg + '\x1b[0m' for arg in args[0].args)
return fn(*args)
return new
sh.emit = decorate_emit(sh.emit)
logger.addHandler(sh)其中有一个缺陷:我无法控制***在模式中的位置,但正如我所说的,它是合适的。
https://stackoverflow.com/questions/20706338
复制相似问题