Python 日志记录删除/检查/修改由 fileConfig() 配置的处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3630774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:00:23  来源:igfitidea点击:

logging remove / inspect / modify handlers configured by fileConfig()

pythonlogging

提问by Pawel Furmaniak

How can I remove / inspect / modify handlers configured for my loggers using the fileConfig() function?

如何使用 fileConfig() 函数删除/检查/修改为我的记录器配置的处理程序?

For removing there is Logger.removeHandler(hdlr) method, but how do I get the handler in first place if it was configured from file?

对于删除有 Logger.removeHandler(hdlr) 方法,但是如果它是从文件配置的,我如何首先获取处理程序?

采纳答案by leoluk

logger.handlerscontains a list with all handlers of a logger.

logger.handlers包含一个包含所有记录器处理程序的列表。

回答by perlyking

Another approach might be to use a JSON or YAML config file which gets loaded into a dictionary which you can then view/manipulate before it's passed to the logger.config.

另一种方法可能是使用加载到字典中的 JSON 或 YAML 配置文件,然后您可以在将其传递给 logger.config 之前查看/操作该文件。

import yaml
import logging.config

with open (LOG_CONFIG, 'rt') as f:
   config=yaml.safe_load(f)
   config['handlers']['error_file_handler']['filename']='foo'
logging.config.dictConfig(config)

回答by Mickey Perlstein

This code will print all the loggers and for each logger its handlers

此代码将打印所有记录器以及每个记录器的处理程序

for k,v in  logging.Logger.manager.loggerDict.items()  :
        print('+ [%s] {%s} ' % (str.ljust( k, 20)  , str(v.__class__)[8:-2]) ) 
        if not isinstance(v, logging.PlaceHolder):
            for h in v.handlers:
                print('     +++',str(h.__class__)[8:-2] )

This will print out the loggers and handlers in your system including their states and levels.

这将打印出系统中的记录器和处理程序,包括它们的状态和级别。

This will help you debug your logging issues

这将帮助您调试日志记录问题

output:
+ [root                ] {logging.RootLogger} {DEBUG} 
-------------------------
   -name=root
   -handlers=[<logging.FileHandler object at 0x7fc599585390>, <logging.StreamHandler object at 0x7fc599585550>]
   -filters=[]
   -propagate=True
   -level=10
   -disabled=False
   -parent=None
     +++logging.FileHandler {NOTSET}
   -stream=<_io.TextIOWrapper name='/dev/logs/myapp.log' mode='w' encoding='UTF-8'>
   -mode=w
   -filters=[]
   -encoding=None
   -baseFilename=/home/dev/logs/myapp.log
   -level=0
   -lock=<unlocked _thread.RLock object owner=0 count=0 at 0x7fc5a85a4240>
   -delay=False
   -_name=None
   -formatter=<logging.Formatter object at 0x7fc599585358>
     +++logging.StreamHandler {DEBUG}
   -lock=<unlocked _thread.RLock object owner=0 count=0 at 0x7fc5a85a4210>
   -filters=[]
   -stream=<ipykernel.iostream.OutStream object at 0x7fc5aa6abb00>
   -level=10
   -_name=None
   -formatter=<logging.Formatter object at 0x7fc5995853c8>
+ [PathFinder          ] {logging.Logger} {NOTSET} 
-------------------------
   -name=PathFinder
   -handlers=[]
   -filters=[]
   -manager=<logging.Manager object at 0x7fc5b09757f0>
   -propagate=True
   -level=0
   -disabled=False
   -parent=<logging.RootLogger object at 0x7fc5b09757b8>

回答by Alias_Knagg

The answer by @Mickey-Perlstein was just what I was looking for, but the listing appears to come from a much more complete version than the code provided.
This code is kind of even cruder, but crucially for my use and understanding, includes the root logger

@Mickey-Perlstein 的答案正是我要找的,但清单似乎来自比提供的代码更完整的版本。
这段代码更粗略,但对我的使用和理解至关重要,包括根记录器

import logging

def listloggers():
    rootlogger = logging.getLogger()
    print(rootlogger)
    for h in rootlogger.handlers:
        print('     %s' % h)

    for nm, lgr in logging.Logger.manager.loggerDict.items():
        print('+ [%-20s] %s ' % (nm, lgr))
        if not isinstance(lgr, logging.PlaceHolder):
            for h in lgr.handlers:
                print('     %s' % h)

output:

输出:

<RootLogger root (DEBUG)>
     <TimedRotatingFileHandler /path/to/myapp.log (DEBUG)>
     <StreamHandler <stdout> (DEBUG)>
+ [concurrent.futures  ] <Logger concurrent.futures (DEBUG)> 
+ [concurrent          ] <logging.PlaceHolder object at 0x7f72f624eba8> 
+ [asyncio             ] <Logger asyncio (DEBUG)> 
+ [myapp               ] <Logger myapp (DEBUG)> 
+ [flask.app           ] <Logger flask.app (DEBUG)> 
+ [flask               ] <Logger flask (DEBUG)> 
+ [werkzeug            ] <Logger werkzeug (ERROR)>