python – Dynamically changing log level without restarting the application

python – Dynamically changing log level without restarting the application

fileConfig is a mechanism to configure the log level for you based on a file; you can dynamically change it at any time in your program.

Call .setLevel() on the logging object for which you want to change the log level. Usually youd do that on the root:

logging.getLogger().setLevel(logging.DEBUG)

In addition to the accepted answer: Depending on how you initialized the logger, you might also have to update the loggers handlers:

import logging

level = logging.DEBUG
logger = logging.getLogger()
logger.setLevel(level)
for handler in logger.handlers:
    handler.setLevel(level)

python – Dynamically changing log level without restarting the application

Expanding on sfinkens answer, and Starmans subsequent comment, you can also check the type of the handler to target a specific outputter – for instance:

import logging
logger = logging.getLogger()
for handler in logger.handlers:
    if isinstance(handler, type(logging.StreamHandler())):
        handler.setLevel(logging.DEBUG)
        logger.debug(Debug logging enabled)

Leave a Reply

Your email address will not be published. Required fields are marked *