This is the story when using logrotate with logging in python.
In python2 (it can't be helped), I specified hands in logging.basicConfig and used TimedRotatingFileHandler, but for some reason it wasn't even written to the specified log file, and of course log rotation wasn't done either. But when I run it in python3 it works.
I thought I wasn't sure, so I solved it in a different way, so I'll make a note of it.
Someone said that it doesn't work with some versions of python2, Do you specify this in the first place? I would appreciate it if you could give me some information.
** I wrote it in the postscript, but I got information from the inside of the company and it became clear why it did not work! Thank you. .. ** **
In conclusion, biting TimedRotatingFileHandler into addHandler () worked fine.
import logging
from logging.handlers import TimedRotatingFileHandler
logger = logging.getLogger(__name__)
formatter = "%(asctime)s:%(name)s:%(levelname)s:%(message)s"
handler = TimedRotatingFileHandler(
"/hogehoge/logger.log",
when="M",
backupCount=1
)
logger.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter(formatter))
logger.addHandler(handler)
logger.info("===== START HOGEHOGE =====")
The sources that didn't work are:
import logging
import logging.handlers
logger = logging.getLogger(__name__)
formatter = '%(asctime)s:%(name)s:%(levelname)s:%(message)s'
logging.basicConfig(
level=logging.DEBUG,
format=formatter,
handlers=[logging.handlers.TimedRotatingFileHandler(
filename ='/hogehoge/logger.log',
when="M",
backupCount=1
)]
)
logger.setLevel(logging.INFO)
logger.info("=== START HOGEHOGE ===")
The cause was unknown, but if the above method did not work for the time being, I'm thinking of feeding addHandler.
Depending on the environment, I thought about doing TimedRotatingFileHandler with python2, I set handlers in basicConfig and it didn't work, The reason was apparently not simply supported. .. ..
Certainly, you can see that there are no handlers in the following contents and it cannot be used with basicConfig. It took me a while to read more documents. I learned a lot.
##Contents
The following keyword arguments are supported.
・ Filename
A FileHandler is created with the specified name instead of StreamHandler.
・ Filemode
If filename is specified, open the file in this mode. Defaults to 'a'.
・ Format
Uses the specified formatted string in the handler.
・ Datefmt
Time in the specified date and time format.strftime()Use what is accepted by.
・ Level
Sets the level of the root logger to the specified level.
・ Stream
Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, stream is ignored.
##reference
https://docs.python.org/ja/2.7/library/logging.html
Recommended Posts