Python 设置日志记录级别

Python 设置日志记录级别,python,logging,Python,Logging,我正在尝试使用标准库调试代码: 这很好: import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info('message') 我无法使记录器在较低级别工作: logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) logger.info('messag

我正在尝试使用标准库调试代码:

这很好:

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info('message')
我无法使记录器在较低级别工作:

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.info('message')

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug('message')

这两个问题我都没有得到任何回应。

什么Python版本?这在3.4中对我有效。但请注意,如果已设置根处理程序,则不会影响它:

如果根记录器已经为其配置了处理程序,则此函数不执行任何操作

要在根目录上显式设置级别,请执行
logging.getLogger().setLevel(logging.DEBUG)
。但是,请确保您事先调用了
basicConfig()
,以便根记录器最初有一些设置。即:

import logging
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger('foo').debug('bah')
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('foo').debug('bah')

还请注意,“记录器”及其“处理程序”都有不同的独立日志级别。因此,如果您之前在Python脚本中显式加载了一些复杂的记录器配置,并且这会干扰根记录器的处理程序,那么这可能会产生影响,仅使用
logging.getLogger().setLevel(…)
更改记录器日志级别可能不起作用。这是因为附加的处理程序可以单独设置日志级别。这种情况不太可能发生,您通常不必担心。

我使用以下设置进行日志记录

基于Yaml的配置 创建一个名为logging.yml的yaml文件,如下所示

version: 1

formatters:
    simple:
        format: "%(name)s - %(lineno)d -  %(message)s"

    complex:
        format: "%(asctime)s - %(name)s - %(lineno)d -  %(message)s"


handlers:
    console:
        class: logging.StreamHandler
        level: DEBUG
        formatter: simple

    file:
        class: logging.handlers.TimedRotatingFileHandler
        when: midnight
        backupCount: 5
        level: DEBUG
        formatter: simple
        filename : Thrift.log

loggers:

    qsoWidget:
        level: INFO
        handlers: [console,file]
        propagate: yes

    __main__:   
        level: DEBUG
        handlers: [console]
        propagate: yes
import logging.config
import logging

with open('logging.yaml','rt') as f:
        config=yaml.safe_load(f.read())
        f.close()
logging.config.dictConfig(config)
logger=logging.getLogger(__name__)
logger.info("Contest is starting")
import logging

class locator(object):
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.debug('{} initialized')
Python-主要 “main”模块应该是这样的

version: 1

formatters:
    simple:
        format: "%(name)s - %(lineno)d -  %(message)s"

    complex:
        format: "%(asctime)s - %(name)s - %(lineno)d -  %(message)s"


handlers:
    console:
        class: logging.StreamHandler
        level: DEBUG
        formatter: simple

    file:
        class: logging.handlers.TimedRotatingFileHandler
        when: midnight
        backupCount: 5
        level: DEBUG
        formatter: simple
        filename : Thrift.log

loggers:

    qsoWidget:
        level: INFO
        handlers: [console,file]
        propagate: yes

    __main__:   
        level: DEBUG
        handlers: [console]
        propagate: yes
import logging.config
import logging

with open('logging.yaml','rt') as f:
        config=yaml.safe_load(f.read())
        f.close()
logging.config.dictConfig(config)
logger=logging.getLogger(__name__)
logger.info("Contest is starting")
import logging

class locator(object):
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.debug('{} initialized')
子模块/类 这些应该是这样开始的

version: 1

formatters:
    simple:
        format: "%(name)s - %(lineno)d -  %(message)s"

    complex:
        format: "%(asctime)s - %(name)s - %(lineno)d -  %(message)s"


handlers:
    console:
        class: logging.StreamHandler
        level: DEBUG
        formatter: simple

    file:
        class: logging.handlers.TimedRotatingFileHandler
        when: midnight
        backupCount: 5
        level: DEBUG
        formatter: simple
        filename : Thrift.log

loggers:

    qsoWidget:
        level: INFO
        handlers: [console,file]
        propagate: yes

    __main__:   
        level: DEBUG
        handlers: [console]
        propagate: yes
import logging.config
import logging

with open('logging.yaml','rt') as f:
        config=yaml.safe_load(f.read())
        f.close()
logging.config.dictConfig(config)
logger=logging.getLogger(__name__)
logger.info("Contest is starting")
import logging

class locator(object):
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.debug('{} initialized')

希望这能帮助您……

在我看来,这是大多数情况下的最佳方法

通过INI文件进行配置 在项目根目录中创建文件名
logging.ini
,如下所示:

[记录器]
键=根
[根]
级别=调试
处理程序=屏幕、文件
[格式化程序]
keys=简单、冗长
[格式化程序\u简单]
格式=%(asctime)s[%(levelname)s](name)s:%(message)s
[格式化程序\u详细]
格式=[%(asctime)s]%(levelname)s[%(文件名)s%(名称)s%(funcName)s(%(行号)d)]:%(消息)s
[处理程序]
按键=文件、屏幕
[处理程序文件]
class=handlers.TimedRotatingFileHandler
间隔时间=午夜
备份计数=5
格式化程序=详细
级别=警告
args=('debug.log',)
[处理程序屏幕]
class=StreamHandler
格式化程序=简单
级别=调试
args=(sys.stdout,)
然后按如下方式进行配置:

导入日志
从logging.config导入fileConfig
fileConfig('logging.ini')
logger=logging.getLogger('dev')
name=“stackoverflow”
info(f“Hello{name}!”)
logger.critical('此消息应转到日志文件')
logger.error('这也应该如此')
logger.warning('还有这个')
debug('Bye!')
如果运行脚本,
sysout
将:

2021-01-3103:40:10241[信息]开发者:你好!
2021-01-31 03:40:10242[关键]开发人员:此消息应转到日志文件。
2021-01-3103:40:10243[错误]戴夫:这也应该如此。
2021-01-3103:40:10243[警告]戴夫:还有这个。
2021-01-3103:40:10243[调试]开发人员:再见!
debug.log
文件应包含:

[2021-01-31 03:40:10,242] CRITICAL [my_loger.py dev <module> (12)]: This message should go to the log file.
[2021-01-31 03:40:10,243] ERROR [my_loger.py dev <module> (13)]: So should this.
[2021-01-31 03:40:10,243] WARNING [my_loger.py dev <module> (14)]: And this, too.
[2021-01-31 03:40:10242]关键[my_loger.py dev(12)]:此消息应转到日志文件。
[2021-01-3103:40:10243]错误[my_loger.py dev(13)]:这也应该是错误的。
[2021-01-3103:40:10243]警告[my_loger.py dev(14)]:还有这个。

全部完成。

我想将默认记录器保留在警告级别,但为我的代码提供了详细的低级记录器。但它什么也看不出来。在另一个答案的基础上,事先运行
logging.basicConfig()
是至关重要的

import logging
logging.basicConfig()
logging.getLogger('foo').setLevel(logging.INFO)
logging.getLogger('foo').info('info')
logging.getLogger('foo').debug('info')
logging.getLogger('foo').setLevel(logging.DEBUG)
logging.getLogger('foo').info('info')
logging.getLogger('foo').debug('debug')
预期产出

INFO:foo:info
INFO:foo:info
DEBUG:foo:debug
对于跨模块的日志记录解决方案,我这样做了

# cfg.py

import logging
logging.basicConfig()
logger = logging.getLogger('foo')
logger.setLevel(logging.INFO)
logger.info(f'active')

# main.py

import cfg
cfg.logger.info(f'main')

qsoWidget
仅仅是应用程序的名称吗?在
\uuuu init\uuuuuuuuuy.py
中包含所有日志配置不是最佳做法吗?这是一个问题。我想说-你应该试着把你的日志设置放在项目中可能的最高点。然后让相关模块使用它。这样,您就有了一致的日志记录。对每个模块执行此操作将导致不同级别、不同日志格式的输出。这将使下游原木处理(Humio、Splunk、PIG)更加困难。很好的例子!非常感谢。通过.yaml设置记录器配置听起来是一个非常有效的方法solution@AlexSkorokhod我认为yaml是可读的,但是将日志记录在一个外部文件中,允许您在不接触代码的情况下更改日志级别。您可以立即发送basicConfig a
force=True
,使其工作,即使它已经设置好。