Python logger动态文件名

时间:2010-05-02 16:37:19

标签: python logging

我想以这样的方式配置我的Python记录器,以便记录器的每个实例都应该登录一个与记录器本身名称相同的文件。

e.g:

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

我想保持它的通用性,不想硬编码我可以拥有的所有记录器名称。这可能吗?

3 个答案:

答案 0 :(得分:16)

如何简单地将处理程序代码包装在函数中:

import os
def myLogger(name):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler(os.path.join('/some/path/', name + '.log'), 'w')
    logger.addHandler(handler)
    return logger

log_hm = myLogger('healthmonitor')
log_hm.info("Testing Log") # Should log to /some/path/healthmonitor.log

为了防止创建重复的处理程序,需要注意确保myLogger(name)name只调用一次。通常这意味着将myLogger(name)放在

if __name__ == '__main__':
    log_hm = myLogger('healthmonitor')

主脚本。

答案 1 :(得分:8)

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')

答案 2 :(得分:0)

上述解决方案中使用的方法是正确的,但是在多次调用时会出现添加重复处理程序的问题。这是改进版。

import os
def getLogger(name):
    # logger.getLogger returns the cached logger when called multiple times
    # logger.Logger created a new one every time and that avoids adding
    # duplicate handlers 
    logger = logging.Logger(name)
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler(os.path.join('/some/path/', name + '.log'), 'a')
    logger.addHandler(handler)
    return logger

def test(i):
  log_hm = getLogger('healthmonitor')
  log_hm.info("Testing Log %s", i) # Should log to /some/path/healthmonitor.log

test(1)
test(2)