简体   繁体   中英

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?

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

eg:

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.

Use logging.basicConfig

import logging
logging.basicConfig(level=logging.DEBUG)
L = logging.getLogger(__name__)

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

if __name__ == "__main__":
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM