Python logging and rotating files
Asked Answered
R

4

47

I have a python program that is writing to a log file that is being rotated by Linux's logrotate command. When this happens I need to signal my program to stop writing to the old file and start writing to the new one. I can handle the signal but how do I tell python to write to the new file?

I am opening the file like this:

logging.basicConfig(format='%(asctime)s:%(filename)s:%(levelname)s:%(message)s',filename=log_file, level=logging.INFO)

and writing to it like this:

logging.log(level,"%s" % (msg))

The logging modules look very powerful but also overwhelming. Thanks.

Regretful answered 2/2, 2012 at 3:32 Comment(0)
H
45

Don't use logging.basicConfig, use WatchedFileHandler. Here's how to use it.

import time
import logging
import logging.handlers

def log_setup():
    log_handler = logging.handlers.WatchedFileHandler('my.log')
    formatter = logging.Formatter(
        '%(asctime)s program_name [%(process)d]: %(message)s',
        '%b %d %H:%M:%S')
    formatter.converter = time.gmtime  # if you want UTC time
    log_handler.setFormatter(formatter)
    logger = logging.getLogger()
    logger.addHandler(log_handler)
    logger.setLevel(logging.DEBUG)

log_setup()
logging.info('Hello, World!')
import os
os.rename('my.log', 'my.log-old')
logging.info('Hello, New World!')
Hedve answered 4/2, 2015 at 23:28 Comment(2)
@TyHitzeman You mean RotatingFileHandler. RollingFileHandler is a Java thing.Hedve
This works great for the OP and other Unix users. FYI for Windows users: you can't use WatchedFileHandler according to the docs. Checkout RotatingFileHandler insteadEspouse
M
33

You may want to look at WatchedFileHandler to implement this, or as an alternative, implement log rotation with RotatingFileHandler, both of which are in the logging.handlers module.

Milliary answered 2/2, 2012 at 3:43 Comment(3)
Thanks! If I need to I can go this route but currently the file is already being rotated outside of my code. I was hoping there was a way to close the log and reopen it.Regretful
Ah ... WatchedFileHandler ... now I get it.Regretful
is there an option to have the rolled logs not currently being written to compressed (zipped)? E.g the docs mention that RotatingFileHandler would produce app.log.1, app.log.2, ... but ideally these rolled logs would be optionally compressed to save space.Pons
S
13
from logging import handlers

handler = handlers.TimedRotatingFileHandler(filename, when=LOG_ROTATE)

handler.setFormatter(logging.Formatter(log_format, datefmt="%d-%m-%Y %H:%M:%S"))

#LOG_ROTATE = midnight    
#set your log format

This should help you in handling rotating log

Singlebreasted answered 2/2, 2012 at 4:15 Comment(0)
S
9

Since rotation is already being done by logrotate, in your signal handler you should just call logging.basicConfig(...) again and that should reopen the log file.

Sheepherder answered 24/12, 2013 at 5:42 Comment(1)
basicConfig is a no-op if it's already been run. To force it to reconfigure everything again, you have to set logging.root.handlers = [] first.Coreycorf

© 2022 - 2024 — McMap. All rights reserved.