这是setLogRecordFactory()
CPython 3.7 的全部荣耀:
# https://github.com/python/cpython/blob/29500737d45cbca9604d9ce845fb2acc3f531401/Lib/logging/__init__.py#L386
_logRecordFactory = LogRecord
def setLogRecordFactory(factory):
global _logRecordFactory
_logRecordFactory = factory
def getLogRecordFactory():
return _logRecordFactory
def makeLogRecord(dict):
rv = _logRecordFactory(None, None, "", 0, "", (), None, None)
rv.__dict__.update(dict)
return rv
调用它的地方是 Called in Logger.makeRecord()
:
def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
func=None, extra=None, sinfo=None):
"""
A factory method which can be overridden in subclasses to create
specialized LogRecords.
"""
rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func,
sinfo)
相反,在 Python 2 中,这不是一件事:
# https://github.com/python/cpython/blob/7c2c01f02a1821298a62dd16ecc3a12da663e14b/Lib/logging/__init__.py#L1261
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
"""
A factory method which can be overridden in subclasses to create
specialized LogRecords.
"""
rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
你可以做的是基本上替换对象上的.makeRecord()
绑定方法Logger
。换句话说:
>>> class A:
... def f(self, a, b):
... return a + b
>>> def new_f(self, a, b):
... return a * b
...
>>> A.f = new_f
>>> A().f(10, 20)
200
这看起来像:
class MyLogRecord(logging.LogRecord):
pass
# override stuff here
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
print "Using a MyLogRecord instance"
rv = MyLogRecord(name, level, fn, lno, msg, args, exc_info, func)
if extra is not None:
for key in extra:
if (key in ["message", "asctime"]) or (key in rv.__dict__):
raise KeyError("Attempt to overwrite %r in LogRecord" % key)
rv.__dict__[key] = extra[key]
return rv
logging.Logger.makeRecord = makeRecord
插图:
>>> logging.error("hello")
Using a MyLogRecord instance
ERROR:root:hello
在这种情况下,您只是根据使用单个其他MyLogRecord
类的特定需求进行定制。如果你真的想要,你可以编写你自己的setLogRecordFactory()
,如上所示,然后_logRecordFactory
在你的替换.makeRecord()
方法中使用,就像 Python 3 正在做的那样。
假设/替代(子类,不要替换)
还有一条评论:这一切都假设您想要影响logger
在其他地方创建的非“您自己的”实例。如果您只想影响您自己的代码定义的记录器,您可以只子类 Logger
化而不是完全替换Logger
属于logging.__init__
模块命名空间的类。