Skip to main content
 首页 » 编程设计

python之为什么 python 不将异常记录到 syslog(但它确实记录了)

2025年05月04日10webabcd

documentation对于 Python 2.x 的 emit() 函数 SysLogHandler说:

The record is formatted, and then sent to the syslog server. If exception information is present, it is not sent to the server.

...为什么? source没有 tell我很多。我错过了什么吗?

但是,当我尝试以下代码时:

import logging 
from logging.handlers import SysLogHandler 
 
rootlogger = logging.getLogger() 
rootlogger.setLevel(logging.DEBUG) 
syslogh = SysLogHandler('/dev/log') 
rootlogger.addHandler(syslogh) 
# to see what's happening too 
consoleh = logging.StreamHandler() 
rootlogger.addHandler(consoleh) 
 
# this appears in the log 
rootlogger.info('foobar') 
try: 
    a = 42 
    a / 0 
except ZeroDivisionError as e: 
    rootlogger.exception('myException!: {}'.format(e)) 

它确实将以下内容写入系统日志:

May 7 16:25:59 localhost foobar
May 7 16:25:54 localhost myException!: integer division or modulo by zero#012Traceback (most recent call last):#012 File "syslogonly.py", line 16, in #012 a / 0#012ZeroDivisionError: integer division or modulo by zero

我在 Debian wheezy 系统上使用 rsyslog 8.4.2。

此外,我知道多行存在问题,但这是否相关?

请您参考如下方法:

您没有调用 Logger.emit()。您正在调用 Logger.exception(),根据 documentation , 总是在消息中添加异常信息:

Logs a message with level ERROR on this logger. The arguments are interpreted as for debug(), except that any passed exc_info is not inspected. Exception info is always added to the logging message. This method should only be called from an exception handler.

不过,我没有深入研究源代码来确定调用 emit() 的内容以及在什么情况下调用。