Python,logging:扩展Logger时的错误路径名

时间:2013-04-20 16:40:23

标签: python logging

我正在尝试以这种方式创建自定义记录器:

文件:logger.py

import logging

class Logger(logging.getLoggerClass()):
    def warning(self, msg, *args, **kwargs):
        super(Logger, self).warning(msg, *args, **kwargs)

logging.setLoggerClass(Logger)
log = logging.getLogger('test')
handler = logging.StreamHandler()
formatter = logging.Formatter('%(pathname)s')
handler.setFormatter(formatter)
log.addHandler(handler)

文件:test.py

from logger import log

log.warning('')

输出:

$ python test.py
/home/dario/Desktop/logging_test/logger.py

预期输出为:

/home/dario/Desktop/logging_test/test.py

甚至更奇怪的是,如果我评论setLoggerClass行,我会得到test.py,但没有完整路径。

我做错了什么?谢谢!

在Arch Linux x86_64上使用Python 2.7.4和3.3.1进行测试。

1 个答案:

答案 0 :(得分:0)

来自Python Documentation - Logging - LogRecord attributes

  

%(路径名)s - 发出日志记录调用的源文件的完整路径名(如果可用)。

即。其中logging对象(或任何子类,如Logger)已初始化 在这种情况下,logging及其实例log在同一文件test.py中定义和初始化。

如果我拆分文件,可能会更清楚一点:

logger.py:(班级)

import logging                                           

# This is the path `logging` gets                        
class Logger(logging.getLoggerClass()):                  
    def warning(self, msg, *args, **kwargs):             
        super(Logger, self).warning(msg, *args, **kwargs)

log.py:log模块,其中log对象的类型为Logger

import logging
from logger import Logger

logging.setLoggerClass(Logger)
log = logging.getLogger('test')
handler = logging.StreamHandler()

# Not this file's path, but where class Logger
# creates a logging object with super()
formatter = logging.Formatter('%(pathname)s')
handler.setFormatter(formatter)
log.addHandler(handler)

test.py:(主要)

from log import log

log.warning('')