在 Python 中发送 Json 对象字符串作为系统日志消息

Sending Json Object string as syslog message in Python

我正在使用 this tool 获取设备上的指标。

该脚本正在使用套接字发送系统日志消息,我正在尝试让它使用本机系统日志函数发送消息。

我添加了以下代码,但似乎无法正常工作。

def sendSyslog2(jsonObj):
if (logHostAvailable["syslog"]==True):
    logging.info("SYSLOG REQUEST: "+json.dumps(jsonObj))
    try:
        syslog.openlog(facility=syslog.LOG_LOCAL5)
        syslog.syslog(syslog.LOG_INFO, json.dumps(jsonObj))
    except:
        logging.error("syslog failed")

即使使用测试脚本也是失败的。我不太精通 python 或编程,但我可以通过一些参考来获得,任何正确方向的指针表示赞赏。

发件人:

您可以使用远程系统日志服务器:rsyslog 或 python 包 loggerglue 实现 rfc5424 和 rfc5425 中描述的系统日志协议。 .当您使用高于 1024 的端口时,您可以 运行 作为非根用户。

在 python 日志记录模块中,您有一个 SyslogHandler,它也支持 syslog 远程日志记录。

import logging
import logging.handlers

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

handler = logging.handlers.SysLogHandler(address = ('127.0.0.1',514))

my_logger.addHandler(handler)

my_logger.debug('this is debug')
my_logger.critical('this is critical')