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

痞子三分冷 提交于 2021-02-09 10:49:56

问题


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:


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.



来源:https://stackoverflow.com/questions/36084756/logging-in-a-python-script-is-not-working-results-in-empty-log-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!