【问题标题】:how to prevent the propagation of logging to other modules?如何防止日志记录传播到其他模块?
【发布时间】:2021-10-03 04:51:11
【问题描述】:

我在我的 python 脚本 (myscript.py) 中创建了一个记录器,

logfmt = '[%(asctime)s]{%(filename)s:%(lineno)d}[%(levelname)s] %(message)s'
datefmt = '%Y-%m-%dT%H:%M:%S'
formatter = logging.Formatter(logfmt, datefmt=datefmt)
logging.basicConfig(level=logging.DEBUG, format=logfmt, datefmt=datefmt)
logger = logging.getLogger(name='mine')

在 INFO 级别,它看起来没问题。但是在调试级别,奇怪的是 matplotlib 打印它的日志,显示它导入的很长的模块列表。如何防止它并仅打印我的脚本日志?

[2021-07-27T11:53:48]{myscript.py:183}[INFO] ...

[2021-07-27T11:53:48]{__init__.py:224}[DEBUG] matplotlib data path: /home/user/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data
[2021-07-27T11:53:48]{__init__.py:224}[DEBUG] CONFIGDIR=/home/user/.config/matplotlib
[2021-07-27T11:53:48]{__init__.py:1394}[DEBUG] matplotlib version 3.4.2
[2021-07-27T11:53:48]{__init__.py:1395}[DEBUG] interactive is False
[2021-07-27T11:53:48]{__init__.py:1396}[DEBUG] platform is linux
[2021-07-27T11:53:48]{__init__.py:1397}[DEBUG] loaded modules: ['sys', 'builtins', '_frozen_importlib', '_imp', '_warnings', '_frozen_importlib_external', '_io', 'marshal', 'posix', '_thread', '_weakref', 'time', 'zipimport', '_codecs', 'codecs', 'encodings.aliases', 'encodings', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', '_abc', 'abc', 'io', '_stat', 'stat', '_collections_abc', 
... very only list ...
'cycler', 'matplotlib.rcsetup', 'matplotlib._version', 'matplotlib.ft2font', 'kiwisolver', 'dateutil.rrule', 'matplotlib.units', 'matplotlib.dates']

[2021-07-27T11:53:48]{myscript.py:351}[INFO] ...

【问题讨论】:

  • @blues 没有。并且该 A 的许多 cmets 告诉给记录器一个名称不会改变任何东西 - 与我的测试相同。
  • 你真的试过了吗? basicConfig 将处理程序添加到根记录器,因此建议的解决方案不适用于 basicConfig。

标签: python matplotlib logging


【解决方案1】:

获取matplotlib使用的记录器,然后覆盖其日志级别:

logging.getLogger(name='matplotlib').setLevel(logging.WARNING)

如果您想知道我是如何找到matplotlib 记录器的名称的,请查看How to list all existing loggers using python.logging module(它恰好与模块和包的名称相同,但不一定是)。

【讨论】:

    【解决方案2】:

    没有设置来尝试这个,希望仍然有效。在您的日志配置后添加:

    mpl_logger = logging.getLogger(‘matplotlib’)
    mpl_logger.setLevel(logging.WARNING) 
    

    【讨论】:

      【解决方案3】:

      只需将 matplotlib 的 loglevel 设置为“info” 见https://matplotlib.org/stable/_modules/matplotlib.html#set_loglevel

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-04
        • 2016-02-26
        • 2014-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多