在 Python `logging.handlers.SysLogHander` 中设置 `LOG_*` 选项

Set `LOG_*` options in Python `logging.handlers.SysLogHander`

使用syslog.openlog,我们可以设置一些日志选项,如LOG_NDELAYLOG_NOWAIT,它们在<syslog.h>中定义。我一直在寻找在 logging.handlers.SysLogHander.

上设置这种日志选项的方法

我发现 LOG_CONSLOG_PERROR 可以通过额外的 logging.handers 来实现。 LOG_NDELAY 已经设置,因为连接是在实例化处理程序时打开的。

我不太关心LOG_NOWAIT,因为我主要用Linux。

那么,如何设置LOG_ODELAYLOG_PID

正在查看 the source for syslog.openlog, it directly passes the option integer to openlog(3)

深入研究,glibc 的 openlog calls openlog_internal, which just sets it to the LogStat 全局。

那么,让我们看看您在 openlog(3) 文档中需要的标志:

LOG_ODELAY: The converse of LOG_NDELAY; opening of the connection is delayed until syslog() is called. (This is the default, and need not be specified.)

这似乎只有在您首先 使用 openlog() 时才有意义,而 SysLogHandler 不会这样做;它只是 connects to the syslog over UDP.

你可以实现你自己的 SyslogFormatter,它确实使用 syslog.openlog()syslog.syslog() 并传递你心中想要的所有标志——stdlib 不这样做的原因,我想象一下,它是不可移植的,因为 syslog 模块可能不可用,例如Windows.

LOG_PID: Include PID with each message.

这是在 glibc 中实现的 here

if (LogStat & LOG_PID)
    fprintf (f, "[%d]", (int) __getpid ());

这很容易实现,因为logging already logs process IDs by default and exposes it to formatters

所以只需将格式化程序字符串设置为

"[%(process)s] %(levelname)s:%(name)s:%(message)s"

而不是默认值

"%(levelname)s:%(name)s:%(message)s"