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

And*_*ier 9 python macos logging syslog python-3.x

使用OS X 10.10.4上的Python 3.5,我]在输出系统日志消息中得到虚假字符.这可以通过以下示例程序看到:

#!/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")
Run Code Online (Sandbox Code Playgroud)

如果我运行这个,我看到syslog输出如下:

Dec 16 12:38:33 mymachinename [76399] Test]: ABC
Run Code Online (Sandbox Code Playgroud)

(注意之后的虚假]角色Test).

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

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

OS X 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=
Run Code Online (Sandbox Code Playgroud)

我在Ubuntu 10.04上没有看到同样的问题,因此它似乎是特定于OS X的.

Lia*_*lly 4

更新:

知道了。修复您的格式字符串以遵循 BSD 系统日志格式:

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

你得到:

Aug 23 21:38:02 mymachine [65057]: Test : ABC
Run Code Online (Sandbox Code Playgroud)

背景/原始帖子

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

Aug 23 21:10:15 machine-name [64643] Test]: ABC
Run Code Online (Sandbox Code Playgroud)

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

logger.error("Test  ABC")
Run Code Online (Sandbox Code Playgroud)

然后日志条目就正常了:

Aug 23 21:15:03 machine Unknown: [64701] Test  ABC
Run Code Online (Sandbox Code Playgroud)

我认为冒号被解释为格式化字符,因为您正在使用 BSD 格式化选项。来自BSD 系统日志 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.
Run Code Online (Sandbox Code Playgroud)

那么也许 OS X syslog 试图遵守 BSD Syslog RFC 并且感到困惑?