请帮助我,如何将python脚本日志发送到syslog服务器(syslog-ng产品),我已经尝试过以下方法。它有两种方法。一个与“ SysLogHandler”一起使用,另一个与“ SocketHandler”一起使用]
import logging
import logging.handlers
import socket
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address=('10.10.11.11', 611), socktype=socket.SOCK_STREAM)
#handler = logging.handlers.SocketHandler('10.10.11.11', 611)
my_logger.addHandler(handler)
my_logger.debug('this is debug')
my_logger.critical('this is critical')
结果:用于SysLogHandler
[ansible@localhost ~]$ python test.py
Traceback (most recent call last):
File "test.py", line 8, in <module>
handler = logging.handlers.SysLogHandler(address=('10.10.11.11', 611), socktype=socket.SOCK_STREAM)
File "/usr/lib64/python3.6/logging/handlers.py", line 847, in __init__
raise err
File "/usr/lib64/python3.6/logging/handlers.py", line 840, in __init__
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused #THIS IS OK for me since server unreachable.
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/usr/lib64/python3.6/logging/__init__.py", line 1946, in shutdown
h.close()
File "/usr/lib64/python3.6/logging/handlers.py", line 894, in close
self.socket.close()
AttributeError: 'SysLogHandler' object has no attribute 'socket'
[result: SocketHandler ==> No output
..我不确定它是否在工作。
我不确定通过TCP端口将日志发送到syslog服务器的正确方法。我已经使用了syslogHandler和SocketHandler。
syslogHandler:
使用syslogHandler
我正在获取ConnectionRefusedError
,因为我的远程服务器无法访问,我可能会用用户尝试..except方法。。但是我不确定为什么我会得到AttributeError: 'SysLogHandler' object has no attribute 'socket'
SocketHandler:
Python日志记录模块处理程序页面说,该类用于通过TCP将日志发送到远程。但是我看不到任何输出,并且不确定这是否是将日志发送到syslog服务器的正确方法。
请帮助..
预先感谢。
这不是一个合适的解决方案,如果不是绝对必须使用TCP,我建议您使用UDP。它使用syslog处理程序解决了我的很多问题。 TCP似乎想将消息捆绑在一起,具有讽刺意味的是,它在批处理过程中丢失了一些消息。
[当我在具有启动并正在监听端口611的syslog服务器的计算机上尝试此操作时,它没有在SysLogHandler上引发AttributeError。因此您可能应该设置服务器以侦听该端口以修复该问题