当我使用Python的logging.handlers.SysLogHandler时,Syslog消息显示为"未知"

Nic*_*ack 11 python logging syslog

当我在我的mac上运行时:

import logging.handlers
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

syslog_address = '/var/run/syslog'
logger.addHandler(logging.handlers.SysLogHandler(syslog_address))
logger.error("What the crap?")
Run Code Online (Sandbox Code Playgroud)

它在syslog中显示如下:

Oct 18 19:02:06 nick Unknown[4294967295] <Error>: What the crap?
Run Code Online (Sandbox Code Playgroud)

为什么它是未知的?在剧本名称之后,它不应该足够聪明吗?

Vin*_*jip 15

我认为APP-NAME(表示源)是syslog头中的可选组件.最新版本的SysLogHandler(适用于Python 3.3)包括对APP-NAME的支持(ident根据C syslog API调用),但在早期版本中不可用.看到这个Python问题.

如果您将脚本名称添加到所有消息之前,您将获得所需的效果.例如,

logger.error('foo: What\'s up?')
Run Code Online (Sandbox Code Playgroud)

将显示例如

19/10/2011 13:51:17 foo [2147483647]怎么了?

在日志中.


Spl*_*lee 6

为了得到你需要的东西,你应该在处理程序中添加一个格式化程序,这样你就不必自己手动格式化每条消息.

import logging.handlers
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

syslog_address = '/var/run/syslog'

handler = logging.handlers.SysLogHandler(syslog_address)
# create the formatter
formatter = logging.Formatter('%(name)s: [%(levelname)s] %(message)s')
# plug this formatter into your handler(s)
handler.setFormatter(formatter)

logger.addHandler(handler)
logger.error("What the crap?")
Run Code Online (Sandbox Code Playgroud)

您现在应该发现您在syslog中看到了您期望的条目:

Jul  4 14:34:40 ip-127-0-0-1 script_name.py: [ERROR] What the crap?
Run Code Online (Sandbox Code Playgroud)

  • 似乎处理程序的API在某些版本的Python之间有所不同.我只需要执行以下操作来处理我们的2个环境:try:handler.addFormatter(formatter)除了AttributeError,e:handler.formatter = formatter (2认同)