How can I log from Python to syslog with either SysLogHandler or syslog on Mac OS X *and* Debian (7)

时光毁灭记忆、已成空白 提交于 2020-01-12 07:41:08

问题


I've followed several answers here on SO to no avail.

I'm developing on a Macbook (Yosemite), but our test/production boxes are Debian 7 (using rsyslog). I'm trying to log out to syslog in a way that will work both locally and not.

I tried the option of using SysLogHandler. This works on Mac:

import logging
import logging.handlers
import syslog

h = logging.handlers.SysLogHandler(address='/var/run/syslog', facility=syslog.LOG_LOCAL1)
h.ident = 'works_on_macs'
logger = logging.getLogger('i_am_a_lumberjack')
logger.addHandler(h)

logger.debug("And I don't care")
logger.info('There is a sale on today')
logger.warn('Do not touch the hot stove!')
logger.error('Sorry, times up')
logger.critical('That sure is an ugly tie')

These messages will show up in my mac syslog. However, when I change address='/dev/log' on Debian 7... no dice.

Yet:

import syslog

syslog.openlog(ident='im_a_lumberjack', facility=syslog.LOG_LOCAL1)
syslog.syslog(syslog.WARNING, 'Watch out!')

Works on Debian 7, but not on Mac.

I would really love to be able to get one logging solution that works for both platforms. Obviously the address is going to be different, but I'm already setting that in config.

So how do I get syslog working both for Mac and Debian?

Edit:

As further information - I've discovered that my SysLogHandler seems to maybe not be using the facility(?) right. Messages are being picked up by syslog, but they're going to a catch-all, which makes me believe they're not getting tagged with LOG_LOCAL1


回答1:


Turns out the facility that SysLogHandler expects is not syslog.LOG_LOCAL1 or any of the values in that namespace.

It expects 'local1' or other string as explained in the documentation.

Simply changing

h = logging.handlers.SysLogHandler(address='/var/run/syslog', facility=syslog.LOG_LOCAL1)

to

h = logging.handlers.SysLogHandler(address='/var/run/syslog', facility='local1')

Made everything right on both systems.



来源:https://stackoverflow.com/questions/30125412/how-can-i-log-from-python-to-syslog-with-either-sysloghandler-or-syslog-on-mac-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!