简体   繁体   中英

PYTHON-Logging to file and printing DEBUG statements to console

I have been struggling a lot with printing Debug statements to console (+ to a file) and info just to the file. It's a big module and I am passing logger objects created in main file to all others in the function calls.


logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%Y%m%d %H:%M',
                    filename='full_log.log',
                    filemode='w')

console = logging.StreamHandler()
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')

console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)

logger_1 = logging.getLogger('logger_1')
logger_module = logging.getLogger('module')

logger_1.debug("sample debug")
logger_1.info("sample info")
fil.main(logger_module)

test/fil.py

def main(logger):
    logger.info("Hello logging!")

Both info and debug prints to console and writes to the file too. Can someone please explain what am I doing wrong? How do I set levels to print and write to file?

You are setting the level of the console Handler to DEBUG but you are not setting the level of the FileHandler that is added by basicConfig at all. The level that is set in basicConfig is applied to the root logger, but you are logging with child loggers that propagate.

This bypasses the level of the parent loggers because it directly uses the handlers. This is explained in the documentation here .

Messages are passed directly to the ancestor loggers' handlers - neither the level nor filters of the ancestor loggers in question are considered.

The solution is not to use basicConfig and instead create a logging.FileHandler for which you set the level.

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