gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:28:19 25 4
gpt4 key购买 nike

在 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")

如果我运行它,我会看到这样的系统日志输出:

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

(注意 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=

没有在 Ubuntu 10.04 上看到同样的问题,所以它似乎是特定于 OS X 的。

最佳答案

更新:

明白了。修复您的格式字符串以符合 BSD 系统日志格式:

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 系统日志 RFC 并感到困惑?

关于python - 为什么我在 OS X 上使用 Python 的 SysLogHandler 在 syslog 消息中得到一个虚假的 ']' 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com