为什么我会得到一个虚假的']'在OS X上使用Python的SysLogHandler进行syslog消息中的字符?

时间:2015-12-15 23:42:01

标签: python macos python-3.x logging syslog

在OS X 10.10.4上使用Python 3.5,我在输出syslog消息中得到假的]个字符。这可以通过以下示例程序看出:

#!/usr/bin/env python3

import logging
import logging.handlers

logger = logging.getLogger('test')

syslog_handler = logging.handlers.SysLogHandler(address='/var/run/syslog')
syslog_formatter = logging.Formatter('[{process}] {message}', style='{')
syslog_handler.setFormatter(syslog_formatter)

logger.addHandler(syslog_handler)
logger.error("Test : ABC")

如果我运行它,我会看到这样的syslog输出:

Dec 16 12:38:33 mymachinename [76399] Test]: ABC

(请注意]之后的虚假Test字符。

如果我稍微更改格式化程序字符串以删除最初的[字符,则额外的]会消失。但是,我希望这个文字字符出现在格式化的字符串中(即使它不在格式化字符串的开头,我也有同样的问题。)

为什么会出现虚假的],我该如何避免呢?

OS X' s asl.conf,这是配置日志记录的地方,如下所示。我没有从默认值中修改它:

##
# configuration file for syslogd and aslmanager
##

# authpriv messages are root/admin readable
? [= Facility authpriv] access 0 80

# remoteauth critical, alert, and emergency messages are root/admin readable
? [= Facility remoteauth] [<= Level critical] access 0 80

# broadcast emergency messages
? [= Level emergency] broadcast

# save kernel [PID 0] and launchd [PID 1] messages
? [<= PID 1] store

# ignore "internal" facility
? [= Facility internal] ignore

# save everything from emergency to notice
? [<= Level notice] store

# Rules for /var/log/system.log
> system.log mode=0640 format=bsd rotate=seq compress file_max=5M all_max=50M
? [= Sender kernel] file system.log
? [<= Level notice] file system.log
? [= Facility auth] [<= Level info] file system.log
? [= Facility authpriv] [<= Level info] file system.log
? [= Facility user] [<= Level debug] file system.log

# Facility com.apple.alf.logging gets saved in appfirewall.log
? [= Facility com.apple.alf.logging] file appfirewall.log file_max=5M all_max=

在Ubuntu 10.04上看到相同的问题,因此它似乎是特定于OS X的。

1 个答案:

答案 0 :(得分:4)

更新:

知道了。修复格式化字符串以遵守BSD syslog格式:

syslog_formatter = logging.Formatter('[{process}]: {message}', style='{')
...
logger.error("Test : ABC")

你得到:

Aug 23 21:38:02 mymachine [65057]: Test : ABC

背景/原始帖子

我在OS X 10.11.6上重现了你的错误

Aug 23 21:10:15 machine-name [64643] Test]: ABC

冒号绝对是罪魁祸首。我将消息更改为:

logger.error("Test  ABC")

然后日志条目正常:

Aug 23 21:15:03 machine Unknown: [64701] Test  ABC

我认为冒号被解释为格式化字符,因为您正在使用BSD格式化选项。来自BSD syslog rfc

the first character of the CONTENT field that signifies the conclusion of 
the TAG field has been seen to be the left square bracket character ("["), 
a colon character (":"), or a space character.  This is explained in more 
detail in Section 5.3.

那么OS X系统日志可能会尝试遵守BSD Syslog RFC而感到困惑?

相关问题