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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 correct
I'm having the same issues as @greendino

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.