如何更改Tornado的日志格式

4

我曾经使用logging.basicConfig来设定自己喜欢的日志格式和目标。但是当我开始在应用中使用Tornado WebSockets时,logging.basicConfig所设定的格式和目标被忽略了。所有我的日志信息都被打印到了stdout(而不是我的目标日志文件),并且格式也变成了Tornado的(而不是我的)。我该如何解决这个问题?

2个回答

1

我尝试了一个解决方案,可以覆盖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 ')

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

[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 

...你可以使用自己的格式来获取stdout输出:

::: 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问题,但我想它可能会有所帮助...


0

要将日志记录到日志文件中,请按以下方式运行Tornado:

python app.py --log_file_prefix=mylog.log

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

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

这对我不起作用,因为我正在使用日期来进行程序化地设置文件名。但是你的评论给了我需要的线索,log_file_prefix。我可以这样做:tornado.options.options['log_file_prefix'].set('/opt/logs/my_app.log') tornado.options.parse_command_line(), 我在这个问题的答案中找到了。 - user1332148

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接