Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set logging level in python?

I have the following complete python (3.8.5) code example

import logging
L = logging.getLogger(__name__)

def main():
    L.setLevel(logging.DEBUG)
    L.warning("This is warn")
    L.info("This is info")
    L.debug("This is debug")

if __name__ == "__main__":
    main()

which should print out all three phrases, but only prints the first one (for warning).

How to circumvent this bug?

like image 808
Alex Avatar asked Aug 31 '26 02:08

Alex


1 Answers

You should switch the L.setLevel to logging.basicConfig(level=...)

e.g.:

def main():
    logging.basicConfig(level=logging.DEBUG)
    L.warning("This is warn")
    L.info("This is info")
    L.debug("This is debug")

The method you used, sets the logging level for this logger specifically, meaning the specific logger won't actually do anything when logging on lower leverls - it has nothing to do with the logging level of the process and printing. Using logging.basicConfig you config the process' logging level, so even if you have multiple loggers this level will determine which logging messages come out of the process.

like image 93
bluesummers Avatar answered Sep 02 '26 16:09

bluesummers