tags:

views:

718

answers:

2

I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name?

Because I restart the process every morning the TimedRotatingFileHandler won't work. The project is larger, so I would be interested in keeping the code required for logging into a logging configuration file.

A: 

You may be interested in the TimedRotatingFileHandler see http://docs.python.org/library/logging.html#logging.handlers.TimedRotatingFileHandler

luc
+2  A: 

You can use the TimedRotatingFileHandler. For example:

import logging
import logging.handlers

LOG_FILENAME = '/tmp/log'

# Set up a specific logger with our desired output level
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='D')
log.addHandler(handler)

But this will probably only work if your program runs for more than one day. If your script starts daily in a cron job you're better off manually formatting the filename which you pass to your log handler to include a timestamp.

Patrice