【问题标题】:Python SysLogHandler not working: socket.error 'Connection refused'Python SysLogHandler 不工作:socket.error '连接被拒绝'
【发布时间】:2013-10-08 19:32:37
【问题描述】:

我正在尝试配置 Python 应用程序以使用标准 Linux syslogger 登录到 /var/log/messages。但是,当我尝试创建 syslog 处理程序时,我收到错误 socket.error: [Errno 111] Connection refused

>>> import logging
>>> import logging.handlers
>>> logger = logging.getLogger("my_logger")
>>> logger.setLevel(logging.DEBUG)
>>> handler = logging.handlers.SysLogHandler(facility=logging.handlers.SysLogHandler.LOG_DAEMON, address="/var/log/messages")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/logging/handlers.py", line 715, in __init__
    self._connect_unixsocket(address)
  File "/usr/lib64/python2.6/logging/handlers.py", line 731, in _connect_unixsocket
    self.socket.connect(address)
  File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused

/etc/rsyslog.conf 配置如下:

kern.notice;*.err;local0.info;mail.none;authpriv.none;cron.none;local1.none;daemon.notice /var/log/messages

我猜问题出在 syslog 的配置中,但据我所知,我做对了:

  • 我正在尝试创建 Python SysLogHandler,并告诉它使用哪个文件
  • 我告诉 SysLogHandler 使用 DAEMON 工具
  • rsyslog.conf 设置为将守护程序日志发送到 /var/log/messages(以及其他日志)

我还应该做些什么来完成这项工作吗?

以前我只使用了logging.FileHandler,但这不能正常工作,因为当消息文件换行时,Python 会继续记录到旧文件。

【问题讨论】:

    标签: python logging syslog


    【解决方案1】:

    您需要指向实际的 unix 域套接字,而不是日志文件。 Python docs

    试试这个:

    import logging
    import logging.handlers
    logger = logging.getLogger("my_logger")
    logger.setLevel(logging.DEBUG)
    handler = logging.handlers.SysLogHandler(
        facility=logging.handlers.SysLogHandler.LOG_DAEMON, address="/dev/log")
    

    【讨论】:

    • 太棒了,谢谢。当他们说“您应该用于域套接字的地址”时,我没有意识到文档的含义 - 现在是有道理的。谢谢!
    猜你喜欢
    • 2012-07-20
    • 2013-02-24
    • 1970-01-01
    • 2018-11-07
    • 2015-08-13
    • 2023-03-11
    • 1970-01-01
    • 2013-04-06
    相关资源
    最近更新 更多