1

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?

1 Answer 1

2

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'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.