1
我希望登录到文件以及在终端窗口中显示相同的信息,但颜色很好(使用colorlog或其他跨平台日志着色器)。这是我有:如何使用一个格式化程序记录和使用彩色格式化程序到终端?
import logging
import os
import colorlog
def logger(log_filepath='my_app.log', logger_name='myAppLogger'):
"""Log plain text to file and to terminal with colors"""
logger = logging.getLogger(logger_name)
# Log to file (but not to terminal)
logfile_handler = logging.FileHandler(log_filepath)
plain_formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
logfile_handler.setFormatter(plain_formatter)
logfile_handler.setLevel(logging.DEBUG)
# Logging info level to stdout with colors
terminal_handler = colorlog.StreamHandler()
color_formatter = colorlog.ColoredFormatter(
"%(log_color)s%(levelname)-8s%(reset)s %(asctime)s %(blue)s%(message)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
},
secondary_log_colors={},
style='%'
)
terminal_handler.setLevel(logging.DEBUG)
terminal_handler.setFormatter(color_formatter)
# Add handlers to logger
logger.addHandler(logfile_handler)
logger.addHandler(terminal_handler)
return logger
my_logger = logger()
my_logger.debug('Testing debug')
my_logger.info('Testing info')
my_logger.warning('Testing warning')
my_logger.error('Testing error')
my_logger.critical('Testing critical')
这使我在终端下面的(颜色):
WARNING 2017-01-23 20:30:55,180 Testing warning
ERROR 2017-01-23 20:30:55,180 Testing error
CRITICAL 2017-01-23 20:30:55,181 Testing critical
...这在日志文件中(没有颜色,只是纯文本) :
2017-01-23 20:30:55,180 WARNING Testing warning
2017-01-23 20:30:55,180 ERROR Testing error
2017-01-23 20:30:55,181 CRITICAL Testing critical
为什么级别不正确?
为什么'logfile_handler'使用'color_formatter'而不是'terminal_handler'? – Tagc
谢谢 - 就是这样。但关卡的水平呢? (更新了问题) – fredrik
至于关卡,你需要设置'logger.setLevel(logging.DEBUG)'而不是'terminal_handler.setLevel ...'。我有一个想法,为什么这可能是这种情况,但我会确认,然后作为答案张贴。 – Tagc