本文介绍了Python记录器动态文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以这样一种方式配置Python记录器,以便每个记录器实例都应登录一个名称与记录器本身名称相同的文件.
I want to configure my Python logger in such a way so that each instance of logger should log in a file having the same name as the name of the logger itself.
例如:
log_hm = logging.getLogger('healthmonitor')
log_hm.info("Testing Log") # Should log to /some/path/healthmonitor.log
log_sc = logging.getLogger('scripts')
log_sc.debug("Testing Scripts") # Should log to /some/path/scripts.log
log_cr = logging.getLogger('cron')
log_cr.info("Testing cron") # Should log to /some/path/cron.log
我想保持它的通用性,并且不想对我可以拥有的所有记录器名称进行硬编码.有可能吗?
I want to keep it generic and dont want to hardcode all kind of logger names I can have. Is that possible?
推荐答案
import os
import logging
class MyFileHandler(object):
def __init__(self, dir, logger, handlerFactory, **kw):
kw['filename'] = os.path.join(dir, logger.name)
self._handler = handlerFactory(**kw)
def __getattr__(self, n):
if hasattr(self._handler, n):
return getattr(self._handler, n)
raise AttributeError, n
logger = logging.getLogger('test')
logger.setLevel(logging.INFO)
handler = MyFileHandler(os.curdir, logger, logging.FileHandler)
logger.addHandler(handler)
logger.info('hello mylogger')
这篇关于Python记录器动态文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!