Custom logger not logging above warning level

Viewed 42

I am trying to include a custom logger in my application code to show all the messages for all the severity levels as the .py file will be packaged to .exe and logs would be the right place to trace the issue.

code

# Creating custom logger
logger = logging.getLogger(__name__)

# Creating handlers for the custom logger
f_handler = logging.FileHandler('file.log', 'w')
f_handler.setLevel(logging.DEBUG)

# Creating formatter and adding it to handlers
f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
f_handler.setFormatter(f_format)

# Add handlers to the logger
logger.addHandler(f_handler)

logger.debug("DEBUG message from logger")
logger.warning("This is a warning message from logger.")

I am able to see the Warning message output but not the debug message though the level has been set to DEBUG

1 Answers

Setting the severity level through basicConfig method for the custom logger after its initiation of the class logger throws an attribute error. This is expected as the custom logger should have it's own handler and formatter and can not be inherited from the root class.

AttributeError: 'Logger' object has no attribute 'basicConfig'

The code to be run should be:

# Creating custom logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Creating handlers for the custom logger
f_handler = logging.FileHandler('file.log', 'w')
f_handler.setLevel(logging.DEBUG)

# Creating formatter and adding it to handlers
f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
f_handler.setFormatter(f_format)

# Add handlers to the logger
logger.addHandler(f_handler)

logger.debug("DEBUG message from logger 2")
logger.warning("This is a warning message from logger.")

With this the loggin will also happen in the console. to avoid that, one needs to explicitly create a handler to set the level of severity for

StreamHandler
Related