如何更改Tornado的日志记录格式

时间:2013-03-04 20:46:04

标签: python logging tornado

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

2 个答案:

答案 0 :(得分: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 :(得分:0)

有一个解决方案我尝试在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)

...然后当您使用任何龙卷风的日志流时,如:

### 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 

...你用自己的格式得到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问题,但它可以帮助我猜...

相关问题