我查阅了官方文档,默认格式是%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s', datefmt='%y%m%d %H:%M:%S
,如果我想修改这个格式(比如修改时间显示什么的),应该怎么做呢?
1.更改所有类型的日志格式
from tornado.log import LogFormatter
datefmt = '%Y-%m-%d %H:%M:%S'
fmt = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s'
formatter = LogFormatter(color=True, datefmt=datefmt, fmt=fmt)
root_log = logging.getLogger()
for logHandler in root_log.handlers:
logHandler.setFormatter(formatter)
原理:tornado.options.parse_command_line()
会自动调用enable_pretty_logging
方法,该方法默认会创建一个root logger
,因为父子关系的存在,tornado所有其他logger事件都会触发root logger
,所以修改root logger的格式就能修改tornado所有日志的格式。
2.更改某类型日志的格式,这里以access_log为例
from tornado.log import access_log, gen_log, app_log, LogFormatter
access_log.propagate = False
logHandler = logging.StreamHandler()
datefmt = '%Y-%m-%d %H:%M:%S'
fmt = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s'
formatter = LogFormatter(color=True, datefmt=datefmt, fmt=fmt)
logHandler.setFormatter(formatter)
access_log.addHandler(logHandler)
原理:tornado本身有三种类型的日志流:access_log, gen_log, app_log
。为这些logger添加自定义的handler即可,注意access_log.propagate = False
这段代码必不可少,要不然会触发默认的根logger导致重复日志。
Source code for tornado.log
Basic Logging Tutorial