aitorhh
aitorhh

Reputation: 2451

Overwrite python logging configuration at runtime

I have a basic configuration set in my project

From, for example __init__.py:

import logging
logging.basicConfig(level=logging.INFO)

And I would like to change the global level at runtime after reading user parameters. Is that possible without moving the previous lines after that?

A full example will be something like the following:

logger = logging.getLogger(__name__)

def run():
    parser = OptionParser()
    parser.add_option("--debug", dest="debug",
                      action="store_true",
                      help="flag to indicate if debug should be enabled",
                      default=False)
    (options, args) = parser.parse_args()

    if options.debug:
        # change the logging configuration
        pass
        #logging.basicConfig(level=logging.DEBUG)

    # call the application code

Upvotes: 0

Views: 782

Answers (1)

Alex
Alex

Reputation: 1262

Use Logger.setLevel:

logger = logging.getLogger(__name__)
...

if options.debug:
    logger.setLevel(logging.DEBUG)

EDIT:

If you want to set the level of all loggers currently available you can do something like this:

loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
for logger in loggers:
    logger.setLevel(logging.DEBUG)

Or you can mimic the behavior of logging.basicConfig:

logging.root.setLevel(logging.DEBUG)

Upvotes: 2

Related Questions