Logging in a Python script is not working: results in empty log files
Asked Answered
R

1

5

I had a script with logging capabilities, and it stopped working (the logging, not the script). I wrote a small example to illustrate the problem:

import logging
from os import remove
from os.path import exists


def setup_logger(logger_name, log_file, level=logging.WARNING):
    # Erase log if already exists
    if exists(log_file):
        remove(log_file)
    # Configure log file
    l = logging.getLogger(logger_name)
    formatter = logging.Formatter('%(message)s')
    fileHandler = logging.FileHandler(log_file, mode='w')
    fileHandler.setFormatter(formatter)
    streamHandler = logging.StreamHandler()
    streamHandler.setFormatter(formatter)
    l.setLevel(level)
    l.addHandler(fileHandler)
    l.addHandler(streamHandler)


if __name__ == '__main__':
    setup_logger('log_pl', '/home/myuser/test.log')
    log_pl = logging.getLogger('log_pl')
    log_pl.info('TEST')
    log_pl.debug('TEST')

At the end of the script, the file test.log is created, but it is empty.

What am I missing?

Runstadler answered 18/3, 2016 at 12:45 Comment(0)
S
7

Your setup_logger function specifies a (default) level of WARNING

def setup_logger(logger_name, log_file, level=logging.WARNING):

...and you later log two events that are at a lower level than WARNING, and are ignored as they should be:

log_pl.info('TEST')
log_pl.debug('TEST')

If you change your code that calls your setup_logger function to:

if __name__ == '__main__':
    setup_logger('log_pl', '/home/myuser/test.log', logging.DEBUG)

...I'd expect that it works as you'd like.

See the simple example in the Logging HOWTO page.

Sane answered 18/3, 2016 at 12:51 Comment(2)
the OP is just *****, now i cant write the same problem because it would be marked as duplicate, i had the same problem but my logging level is already correctPatel
I'm having the same issues as @PatelEnvelop

© 2022 - 2024 — McMap. All rights reserved.