I'm using the logging module in Python and I would like it to create a new logfile each time my application is started. The older logfiles shoud be rotated (eg: logfile.txt -> logfile1.txt, etc).
I already found this:
http://docs.python.org/library/logging.html
BaseRotatingHandler is the base class for handlers that rotate log files at a certain point. It is not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler.
The RotatingFileHandler does a rollover at a predetermined size and the TimedRotatingFileHandler does a rollover based on the product of when and interval. Both are not what I want, I want the rotation to happen immediately when my application starts.
Log Rotation and RoatatingFileHandler are usually designed and desirable when the application is running for a very long time (days) and you want the log to keep rotation. Under cases where I have to rotate the log upon restart of the application, I had to do that outside of the Logfile handler, which was easier. It was like, before the log writer call for the first time, I would see if the log file already existed, and if yes, rename it and create a new log file. The renaming should be differentiated from the handler's renaming mechanism.
I might be enough to use
RotatingFileHandler
withoutmaxBytes
, then calldoRollover()
on application start.Yup, seems to work fine. The code below will create a new log file on each application run, with added timestamps for log start and close times. Running it will print the list of available log files. You can inspect them to check correct behavior. Adapted from the Python docs example:
I had a similar requirement to be able to force a log rotation at startup based on a command-line option, but for the logfiles to otherwise rotate on their regular schedule. This was my solution:
Notes:
This has been validated to work if
maxBytes > 0
on aRotatingFileHandler
.This method hasn't been tested with a
TimedRotatingFileHandler
, but should work.This method eliminates the need to maintain a reference to the
RotatingFileHandler
to be rotated; as a result, it can easily be used when configuring logging usinglogging.config
.Simplest way is just to have a date tag in log file name, so when you start app each time you will get a new log file.
e.g.
so each time you will have log like
myapp_2011-Jan-11_12-27-29.log
Another benefit is that you can mix this with RotatingFileHandler to have separate log for each app invocation, where each log itself is further divided into multiple fixed size logs.