简体   繁体   中英

How to set the logging level for logger objects?

I am having trouble finding the bug in my code when I try to log using the logging library. Even though I set the minimum log-level to DEBUG, the logger creates a log-file that starts at WARNING.

import logging

my_logger = logging.getLogger("our logger")  

# Remove all handlers associated with my_logger object. 
# This is only done so that we can run this block mult. times.
for handler in my_logger.handlers[:]:
    my_logger.removeHandler(handler)

# let's create a handler and set the logging level
my_handler_for_file = logging.FileHandler("custom logging.log", mode='w')
my_handler_for_file.setLevel(logging.DEBUG)   
# try to set it to logging.CRITICAL and it will only log CRITICAL, 
# so it does work but neither for DEBUG nor INFO!

# add the handlers to our custom logger
my_logger.addHandler(my_handler_for_file)

# let's create some logs
my_logger.debug('This is a debug message')
my_logger.info('This is an info message')
my_logger.warning('This is a warning message')
my_logger.error('This is an error message')
my_logger.critical('This is a critical message')

This is the output in the log-file:

This is a warning message  
This is an error message  
This is a critical message

And this is what I expect it to be:

This is a debug message  
This is an info message  
This is a warning message  
This is an error message  
This is a critical message

Does anyone have an idea what is wrong here?

You need to set the level on the logger too.

my_logger.setLevel(logging.DEBUG)

This is because both the loggers and the handlers filter messages based on their 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