在WSGI中覆盖日志类无效
我为我的Django网站实现了一个自定义的日志记录器:
class SpecialLogger(logging.Logger):
def __init__(self, name, level=logging.DEBUG):
logging.Logger.__init__(self, name, level)
def special(self, msg, *args, **kwargs):
self.log(self.level, msg, *args, **kwargs)
在我的wsgi文件中,我添加了以下几行:
import logging
from testbed.utils import SpecialLogger
logging.setLoggerClass(SpecialLogger)
在我的Django视图中:
1 import logging
2 logger = logging.getLogger('mylog')
3 print str(logging.getLoggerClass())
4 print str(logger)
5 print dir(logger)
第3行打印出 testbed.utils.SpecialLogger
第4行打印出 <logging.Logger instance at 0x21aadcac>
而第5行(当然)没有显示我的函数 special
我哪里做错了?为什么第3行和第4行的结果不一致呢?
1 个回答
0
setLoggerClass 函数的作用是设置一个类,这个类会被用来创建所有在这个函数调用之后的新日志记录器。但是,在这个函数调用之前创建的日志记录器,仍然会使用默认的 logging.Logger 类。你可以在你的 wsgi 文件中加一行代码来确认是否使用了正确的类,比如:
import logging
from testbed.utils import SpecialLogger
logging.setLoggerClass(SpecialLogger)
logger = logging.getLogger('mylog') # should be a testbed.utils.SpecialLogger
如果这样做没有达到你想要的效果,那可能是因为在上面的代码运行之前,还有其他代码(比如在 settings.py
文件中)已经创建了日志记录器。