您可能知道python日志记录模块支持definition of *kwargs自定义日志条目。这似乎不支持logging exceptions。
我的问题:是否有一种简单的方法可以使用logging.exception自定义kwargs?
最小的例子如下:
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:一点背景,我正在编写一个带有线程的进程,我想以下列方式记录信息:
[APP-线程1] [应用-线程2] ...
答案 0 :(得分:7)
你可以使用例如。
logger.error('Message with %s', 'args', exc_info=1, extra={...})