如何更改Tornado的日志格式

4 投票
2 回答
2973 浏览
提问于 2025-04-17 17:55

我之前设置了一个我喜欢的日志格式和目标,使用的是 logging.basicConfig。后来我在我的应用程序中开始使用 Tornado 的 WebSockets,但现在我设置的格式和目标都被忽略了。我的所有日志信息都被打印到了标准输出(也就是屏幕上),而不是我指定的日志文件,而且格式也变成了 Tornado 自己的格式,而不是我自己的。请问我该怎么解决这个问题?

2 个回答

0

要把你的日志记录到日志文件里,可以这样运行Tornado:

python app.py --log_file_prefix=mylog.log

更新:正如下面评论所说,这可能是设置日志文件的更好方法:

tornado.options.options['log_file_prefix'].set('mylog.log')
tornado.options.parse_command_line()
1

我试过一种方法,可以改变 Tornado 日志记录器在标准输出(stdout)上的默认格式(这个方法似乎对三种日志记录器都有效: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 的问题,但我想这可能会有帮助……

撰写回答