4

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

4

2 回答 2

1

我尝试了一个解决方案来覆盖标准输出流级别的龙卷风记录器的默认格式(它似乎适用于所有三个: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 ')

...而不是默认的 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 

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

::: 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 问题,但它可以帮助我猜......

于 2018-03-18T21:06:40.747 回答
0

To direct your logging to your logfile run Tornado like this:

python app.py --log_file_prefix=mylog.log

Update: As stated in the below comment this is probably a better way to setup your log files:

tornado.options.options['log_file_prefix'].set('mylog.log')
tornado.options.parse_command_line()
于 2013-03-05T16:29:44.847 回答