How to print logs in Python Tornado framework by date
This article mainly introduces how to print logs in the Tornado framework of Python by date. For more information, see
After website traffic comes up, logs are stored daily or even hourly for easier viewing and management. The Python logging module also provides TimedRotatingFileHandler to support archiving logs in different time dimensions.
However, according to the official guide of Logging HOWTO, it is found that only root logs are left, and logger in Tornado does not take effect.
According to an answer in stackoverflow, I found that the following configuration allows logger in Tornado to use TimedRotatingFileHandler:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Logging. yaml Version: 1 Disable_existing_loggers: false Formatters: Simple: Format: '% (asctime) s-% (name) s-% (levelname) s-% (message) s' Loggers: All: Handlers: [all] Propagate: false Tornado: Handlers: [all] Propagate: false Handlers: Console: Class: logging. StreamHandler Level: INFO Formatter: simple Stream: ext: // sys. stdout All: Class: logging. handlers. TimedRotatingFileHandler Level: INFO Formatter: simple When: midnight Filename:./logs/server. log Root: Level: INFO Handlers: [console, all] Propagate: true |
You only need to call the code at the Tornado entry:
?
1 |
Logging. config. dictConfig (yaml. load (open ('logging. yaml', 'R '))) |
If you want to split logs by other time dimensions, you can modify the value corresponding to the when parameter.
Note: when the value of when is D, it indicates that logs are archived every 24 hours starting from the start time of the server. If you want to archive logs in the early morning of every day like you, it can be configured as midnight.
To use Centos, install python-yaml: sudo yum install python-yaml first.