gammapoint
gammapoint

Reputation: 1153

Using python logging with WatchedFileHandler

I'm trying to set up a logger which logs stuff from my script. Occasionally I will move this logfile over to another named file for archiving, and I want the logfile to be recreated if it's missing. As I understand, this is what WatchedFileHandler does. However, in the past I've only set up loggers using the basicConfig setup, and never added handlers explicitly. I tried to do this with the following code snippet

logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',level=logging.DEBUG,filename='logfile',filemode='w',datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging.getLogger()
log_handler = logging.handlers.WatchedFileHandler('logfile')
logger.addHandler(log_handler)

but this didn't really work. The logfile was indeed recreated after I had moved it over to another name on disk, but my logging format was not present in the logfile. I tried running basicConfig after I called getLogger() too but that didn't help either.

What am I doing incorrectly here?

Upvotes: 1

Views: 3271

Answers (1)

Vinay Sajip
Vinay Sajip

Reputation: 99365

You need to add a Formatter instance to the handler which has the desired format (basicConfig() does this for you for the handler added to the root logger).

log_handler.setFormatter(logging.Formatter('%(levelname)s:%(asctime)s:%(message)s'))

Upvotes: 2

Related Questions