简体   繁体   中英

How to change Tornado's logging format

I had a logging format and target I liked, set using logging.basicConfig. I started using Tornado WebSockets in my application and now the formatting and target I set, using logging.basicConfig, are being ignored. All of my log messages are being printed to stdout (instead of my target log file) and the formatting is Tornado's (instead of my own). How do I fix this?

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()

There is a solution I tried out to override default format of tornado loggers at the stdout stream level (it seems to work with all three of them : 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)

... and then when you use any of the tornado's logging streams like :

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

... instead of the default 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 

... you get stdout with your own format like :

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

I know this solution doesn't directly answer to your basicConfig problem but it could help I guess ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM