从 python 脚本登录到 rsyslog 工具

Log to rsyslog facility from a python script

我的/etc/rsyslog.conf里有这个:

local0.*     /var/log/local.log

我有一个简单的 python 脚本,它从标准输入读取并应该发送到 local0

#!/usr/bin/python3

import sys, syslog

syslog.openlog(ident="MY_SCRIPT", facility=syslog.LOG_LOCAL0)

for line in sys.stdin:
    syslog.syslog(syslog.LOG_WARNING, f"Message\n\n")

但是没有用。 rsyslog 未将消息视为发送至 local0

只有当我更改为 *.* 时,rsyslog 才能看到它:

*.*     /var/log/local.log

我假设我没有在 python 脚本中正确配置工具。

如何指定我要登录到 local0

Rsyslog 和本地*:

Rsyslog have the facilities local0 to local7 that are "custom" unused facilities that syslog provides for the user. If a developer create an application and wants to make it log to syslog, or if you want to redirect the output of anything to syslog (for example, Apache logs), you can choose to send it to any of the local# facilities. Then, you can use /etc/syslog.conf (or /etc/rsyslog.conf) to save the logs being sent to that local# to a file, or to send it to a remote server (source).

配置:

/etc/rsyslog.conf

local0.*     /var/log/local.log

这是正确的,它将日志文件 /var/log/local.log 分配给登录到 local0 的应用程序。作为另一个示例,kern.=warn -/var/log/kernel/warnings.log 可用于记录内核警告。

Python application/script:

#!/usr/bin/python3
import sys, syslog

syslog.openlog(ident="MY_SCRIPT", facility=syslog.LOG_LOCAL0)

for line in sys.stdin:
    syslog.syslog(syslog.LOG_WARNING, f"Message {line}\n\n")

初始代码确实有效,正如评论中所指出的那样,this 可以用作替代方法,并且已按照@apoorva-kamath 的建议添加了 {line} 变量...

这里的重要方面是 Python 脚本和 Rsyslog 之间的通信。

另外,命令 try 上指出的是重新加载 rsyslog systemctl restart rsyslog;您还可以使用 rsyslogd -N1 检查 Rsyslog 配置并检查 rsyslog 是否正常工作:

sudo cat /var/log/messages | grep rsyslog

根据 Python 脚本 运行 上下文,与 Rsyslog 的通信可能会失败,需要有关您的配置的更多详细信息,否则您可以尝试(从脚本的上下文):

logger -p local0.error "TroubleshootingTest"

最后检查数据传输:

sudo netstat -taupn | grep syslog

文档:

有关 Python syslog, troubleshooting Rsyslog and Rsyslog facility

的更多详细信息