Skip to main content
 首页 » 编程设计

python之如何更改 Tornado 的日志格式

2025年05月04日8soundcode

我有一个我喜欢的日志记录格式和目标,使用 logging.basicConfig 设置。我开始在我的应用程序中使用 Tornado WebSockets,现在我使用 logging.basicConfig 设置的格式和目标被忽略了。我所有的日志消息都被打印到标准输出(而不是我的目标日志文件)并且格式是 Tornado 的(而不是我自己的)。我该如何解决?

请您参考如下方法:

有一个解决方案我尝试在标准输出流级别覆盖 Tornado 记录器的默认格式(它似乎适用于所有三个:app_log、gen_log、access_log):

import logging 
from tornado.log import app_log, gen_log, access_log, LogFormatter 
 
# define your new format, for instance : 
my_log_format = '%(color)s::: %(levelname)s %(name)s %(asctime)s ::: %(module)s:%(lineno)d in %(funcName)s :::%(end_color)s\ 
                 \n %(message)s\n'  
 
# create an instance of tornado formatter, just overriding the 'fmt' arg 
my_log_formatter = LogFormatter(fmt=my_log_format, color=True) 
 
# get the parent logger of all tornado loggers : 
root_logger     = logging.getLogger() 
 
# set your format to root_logger 
root_streamhandler = root_logger.handlers[0] 
root_streamhandler.setFormatter(my_log_formatter) 

... 然后当您使用任何 Tornado 的日志流时,例如:

### let's say we log from your 'main.py' file in an '__init__' function :  
 
app_log.info('>>> this is app_log') 
gen_log.info('>>> this is gen_log ') 
access_log.info('>>> this is access_log ') 

...而不是默认的标准输出:

[I 180318 21:14:35 main:211] >>> this is app_log  
[I 180318 21:14:35 main:212] >>> this is gen_log  
[I 180318 21:14:35 main:213] >>> this is access_log  

...您会得到带有您自己格式的标准输出,例如:

::: INFO tornado.application 180318 21:14:44 ::: main:211 in __init__ :::                    
>>> this is app_log  
 
::: INFO tornado.general 180318 21:14:44 ::: main:212 in __init__ :::                                
>>> this is gen_log  
 
::: INFO tornado.access 180318 21:14:44 ::: main:213 in __init__ :::                                 
 >>> this is access_log  

我知道这个解决方案不会直接回答您的 basicConfig 问题,但我猜它可能会有所帮助......