正如您可能知道的那样,python 日志记录模块支持定义 *kwargs来自定义日志条目。这似乎不支持记录异常。
我的问题:有没有一种简单的方法可以将自定义 kwargs 与 logging.exception 一起使用?
一个最小的例子如下:
import logging
import logging.handlers
def create_logger():
""" initialize logging using sys log
"""
logger = logging.getLogger()
form = '%(asctime)s [%(levelname)-8s] %(xyz)s %(message)s'
local_log_handler = logging.handlers.SysLogHandler(address='/dev/log')
formatter = logging.Formatter(form)
local_log_handler.setFormatter(formatter)
logger.addHandler(local_log_handler)
return logger
log = create_logger()
try:
raise AttributeError("whatever")
except:
log.warn('Alarm! Fire!', extra={'xyz':'POLICE'})
log.exception('')
输出:
Traceback (most recent call last):
File "logexample.py", line 27, in <module>
log.exception('')
File "/usr/lib/python2.7/logging/__init__.py", line 1172, in exception
self.error(msg, exc_info=1, *args)
File "/usr/lib/python2.7/logging/__init__.py", line 1166, in error
self._log(ERROR, msg, args, **kwargs)
File "/usr/lib/python2.7/logging/__init__.py", line 1258, in _log
self.handle(record)
File "/usr/lib/python2.7/logging/__init__.py", line 1268, in handle
self.callHandlers(record)
File "/usr/lib/python2.7/logging/__init__.py", line 1308, in callHandlers
hdlr.handle(record)
File "/usr/lib/python2.7/logging/__init__.py", line 748, in handle
self.emit(record)
File "/usr/lib/python2.7/logging/handlers.py", line 791, in emit
msg = self.format(record) + '\000'
File "/usr/lib/python2.7/logging/__init__.py", line 723, in format
return fmt.format(record)
File "/usr/lib/python2.7/logging/__init__.py", line 467, in format
s = self._fmt % record.__dict__
KeyError: 'xyz'
系统日志:
Jul 30 14:56:27 localhost 2012-07-30 14:56:27,131 [WARNING ] POLICE Alarm! Fire!
PS:一点背景,我正在写一个线程的进程,我想以以下方式记录信息:
[应用线程1] [应用线程2] ...