Peter van Arkel
Peter van Arkel

Reputation: 589

Why is RotatingFileHandler not appending to file

Consider the following code:

def setup_logging(logdir=None, scrnlog=True, txtlog=True, loglevel=logging.DEBUG):
logdir = os.path.abspath(logdir)

if not os.path.exists(logdir):
    os.mkdir(logdir)

log = logging.getLogger('pobsync')
log.setLevel(loglevel)

log_formatter = logging.Formatter("%(asctime)s - %(levelname)s :: %(message)s")

if txtlog:
    txt_handler = RotatingFileHandler(os.path.join(logdir, "pobsync.log"), mode='a', maxBytes=100000)
    txt_handler.doRollover()
    txt_handler.setFormatter(log_formatter)
    log.addHandler(txt_handler)

if scrnlog:
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    log.addHandler(console_handler)

The logging itself works perfectly; I just call my script with log.LEVEL() and it logs nicely to the defined logfile, just as I want it. However, for some reason my logs aren't appending at all, but overwrites the logfile each time instead of appending to it like it should. If I use backupCount=$number in RotatingFileHandler, it still doesn't append, but makes a new logfile (in the expected RotatingFileHandler pattern) up to $number and then rotates them away eventually.

I'm very likely overlooking something here, but for the love of me I can't find the problem at all.

I hope someone here can help me out and hit me with a cluebat, thanks!

Upvotes: 4

Views: 2755

Answers (1)

tdelaney
tdelaney

Reputation: 77337

The problem is that you are doing a rollover right after setting up the handler. You aren't overwriting the log, you are just archiving the current log to pobsunc-1.log. Just remove

txt_handler.doRollover()

See rotatingfilehandler

(update)

Since backupCount defaults to 0, your call to doRollover doesn't create pobsync-1.log, it really does delete it. Rotating logs are more useful if you set backupCount greater than 0.

Upvotes: 3

Related Questions