0

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

1
  • See my answer below for your question, just pointing out that optparse module has been deprecated, please switch to using argparse Commented Jul 5, 2019 at 20:18

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

This solution configures the level at a given logger (in the same file), it does not applies to all the available loggers like logger.basicConfig does.
Thanks for the solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.