Sunday, December 21, 2014

Python logging

module has several interesting types of handlers, useful if you want your log files to roll over, like RotatingFileHandler and TimedRotatingFileHandler. The former is useful if you want to limit log file size, but I wanted my logs to roll over at midnight, so I went with the later.

What I didn't know is that TimedRotatingFileHandler has to be created before the moment of rollover and be present during or after it for the rollover to occur. So if your code runs occasionaly and you create your TimedRotatingFileHandler only when you need it, it's not of any help to you.

But there's a simple solution - when creating my FileHandler I just give it the name of the log file which includes current date!

log_fname = "log-{0}.log".format(datetime.now().strftime("%Y-%m-%d"))
log_full_fname = os.join(LOG_PATH, log_fname)
file_handler = logging.FileHandler(log_full_fname)
It works for me since I create the handler every time I need to log something.

No comments:

Post a Comment