如何仅在 Python 中为模块设置日志记录级别?

Iva*_*van 2 python logging python-3.x

logging.info用来输出关于我的脚本正在做什么的信息,我正在使用它logging.basicConfig(level=logging.INFO)来启用它。而且这个 ( logging.basicConfig(level=logging.INFO)) 也会影响我调用的其他模块(例如 SQLAlchemy),导致输出比我想要的要详细得多。我可以将我的实际脚本的日志记录级别设置为 INFO 而不是它使用的第 3 方模块(我更希望它是警告他们)?

Dan*_*man 5

执行此操作的正常方法是在模块的开头为当前模块定义一个记录器 - 通常基于文件名 - 并在整个过程中引用它。

import logging

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

def function_that_logs():
    logger.info('will log')   # note, using logger not logging
    logger.debug('will not log')
Run Code Online (Sandbox Code Playgroud)