简体   繁体   中英

Python Log, Not Writing to File

So I am trying to implement logging within my Python program. The goal is to set it up so that a log file is created and everything the program does through it's various modules is logged (based on logging level). This is what my current code looks like:

Text File for Log Configuration:

#logging.conf
[loggers]
keys=root,MainLogger

[handlers]
keys=consoleHandler

[formatters]
keys=consoleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_MainLogger]
level=DEBUG
handlers=consoleHandler
qualname=MainLogger
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=consoleFormatter
args=(sys.stdout,)

[formatter_consoleFormatter]
format=%(asctime)s | %(levelname)-8s | %(filename)s-%(funcName)s-%lineno)04d | %(message)s

External Module to Test Logs:

#test.py
import logging

logger = logging.getLogger(__name__)

def testLog():
    logger.debug("Debug Test")
    logger.info("Info Test")
    logger.warning("Warning Test")
    logger.error("Error Test")

Main file:

#__init__.py
import logging
import logging.config
from datetime import datetime

logging.config.fileConfig('logging.conf', disable_existing_loggers = False)
logger = logging.getLogger('MainLogger')
fileHandler = logging.FileHandler('{:%Y-%m-%d}.log'.format(datetime.now()))
formatter = logging.Formatter('%(asctime)s | %(levelname)-8s | %(lineno)04d | %(message)s')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)

if __name__ == "__main__":

    import test
    logger.debug("Debug Test")
    test.testLog()

Currently, all log messages are currently being displayed withing the IDLE3 shell when I run __init__.py and the log file is being created. However within the log file itself the only message being recording is the "Debug Test" from __init__.py . None of the messages from the test.py module are being recorded in the log file.

What is my problem?

In test.py it grabs a logger object before you configure it later in your __init__.py . Make sure you configure the logging module first before grabbing any logger instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM