简体   繁体   中英

How do I set the Python log level?

Running this

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.warning("warning")
logger.info("info")
logger.debug("debug")

only prints "warning". I expect it to print all three messages. What am I doing wrong?

I know this should be the most basic thing in the world, but it's got me stumped, and the Python documentation is confusing on this point.

You never called logging.basicConfig() (or something similar) to establish any handlers. As a result, the call to logger.warning calls it for you, which resets the logging level to logging.WARNING . (Technically, the documentation only mentions the module-level functions logging.warning et al. calling logging.basicConfig for you, so I don't know if this explanation is entirely correct. Calling basicConfig does, however, solve the problem.)

import logging

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.warning("warning")
logger.info("info")
logger.debug("debug")

I figured this out almost immediately after asking.

import logging

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

logging.warning("warning")
logging.info("info")
logging.debug("debug")

The documentation is confusing because it leaps into the details of logger customization without putting the bare minimum module-level example up front. Hopefully, this post can help correct that.

This is essentially the same question asSet logging levels , but I'm leaving my answer up because it is slightly more minimal than the one there.

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