如何使用fileConfig()函数删除/检查/修改为记录器配置的处理程序?
要删除有Logger.removeHandler(hdlr)方法,但如果从文件配置处理程序,我如何首先获得处理程序?
答案 0 :(得分:50)
logger.handlers
包含一个包含记录器所有处理程序的列表。
答案 1 :(得分:3)
另一种方法可能是使用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)
答案 2 :(得分:2)
此代码将打印所有记录器,并为每个记录器打印其处理程序
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] )
这将打印出系统中的记录器和处理程序,包括其状态和级别。
这将帮助您调试日志记录问题
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>
答案 3 :(得分:2)
@ 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)
输出:
<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)>
答案 4 :(得分:0)
重新删除处理程序-如果有帮助的人想要删除我创建的所有日志(我正在学习python日志记录)的所有处理程序,并提出以下建议:
def log_close():
# get all loggers
loggers = [logging.getLogger(name) if 'your_app_name' in name else None for name in logging.root.manager.loggerDict]
# for each valid logger remove all handlers
for log in loggers:
if log != None:
while bool(len(log.handlers)):
for handler in log.handlers:
log.removeHandler(handler)
# set up log
log = logging.getLogger('your_app_name')
log.setLevel('DEBUG')
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
date_format = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(log_format, date_format)
log_filename = 'your_app_name.log'
log_write_mode = 'w+'
file_handler = logging.FileHandler(log_filename, log_write_mode)
file_handler.setFormatter(formatter)
log.addHandler(file_handler)
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
log.addHandler(console_handler)