[英]How to change Tornado's logging format
我有自己喜歡的日志記錄格式和目標,可以使用logging.basicConfig進行設置。 我開始在應用程序中使用Tornado WebSockets,現在忽略了使用logging.basicConfig設置的格式和目標。 我所有的日志消息都被打印到stdout(而不是我的目標日志文件),格式是Tornado的(而不是我自己的)。 我該如何解決?
要將日志定向到日志文件,請按以下方式運行Tornado:
python app.py --log_file_prefix=mylog.log
更新:如以下注釋中所述,這可能是設置日志文件的更好方法:
tornado.options.options['log_file_prefix'].set('mylog.log')
tornado.options.parse_command_line()
我嘗試了一種解決方案,以在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 ')
...而不是默認的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問題,但可以幫助我猜測...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.