在Python中将消息发送到远程syslog服务器时的自定义异常处理

2024-05-20 20:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我正在编写一个syslog客户机,它将向远程syslog服务器发送消息。到目前为止,这是工作相当不错,但我遇到了以下问题。你知道吗

当syslog服务器由于某种原因关闭时,我需要捕获这个消息,以便程序停止发送syslog消息,我们可以调查这个问题。你知道吗

不幸的是,程序继续运行,没有看到TCP套接字已关闭并引发异常。你知道吗

我只在终端收到回溯:

--- Logging error --- Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\logging\handlers.py", line 941, in emit
    self.socket.sendall(msg) ConnectionAbortedError: [WinError 10053]  Call stack:
File "c:\Users\Administrator\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\ptvsd_launcher.py", line 45, in <module>
    main(ptvsdArgs)
File "c:\Users\Administrator\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\__main__.py", line 265, in main
    wait=args.wait)
File "c:\Users\Administrator\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\__main__.py", line 258, in handle_args
    debug_main(addr, name, kind, *extra, **kwargs)
File "c:\Users\Administrator\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_local.py", line 45, in debug_main
    run_file(address, name, *extra, **kwargs)
File "c:\Users\Administrator\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_local.py", line 79, in run_file
    run(argv, addr, **kwargs)
File "c:\Users\Administrator\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_local.py", line 140, in _run
    _pydevd.main()
File "c:\Users\Administrator\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_vendored\pydevd\pydevd.py", line 1925, in main
    debugger.connect(host, port)
File "c:\Users\Administrator\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_vendored\pydevd\pydevd.py", line 1283, in run
    return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
File "c:\Users\Administrator\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_vendored\pydevd\pydevd.py", line 1290, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script       
File "c:\Users\Administrator\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_vendored\pydevd\_pydev_imps\_pydev_execfile.py", line 25, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "c:\Users\Administrator\OneDrive\Documents\Python Scripts\testlogger.py", line 71, in <module>
    my_logger.info(i) Message: 'test4' Arguments: ()

相关代码:

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.ERROR)
my_logger.setLevel(logging.INFO)
my_logger.setLevel(logging.DEBUG)
try:
    handler = logging.handlers.SysLogHandler(('IP ADDRESS HOST', 514), socktype=socket.SOCK_STREAM)
    my_logger.addHandler(handler)
except Exception as e:
    print (e)

list1 = ['test','test2','test3','test4','test5','test6','test7','test8']


for i in list1:
    try:
        my_logger.info(i) #here i expected that an exception would be raised when the TCP socket is not alive anymore
    except Exception as e:
        print (e)

如何确保程序停止并执行适当的异常处理?你知道吗

谢谢!你知道吗


Tags: inpymainmyliblineextensionsvscode
1条回答
网友
1楼 · 发布于 2024-05-20 20:21:43

我切换到另一个解决方案并停止使用SyslogHandler类。你知道吗

我现在使用下面的类,我通过套接字编写了自己的syslog发送器。你知道吗

class Syslog:
  def __init__(self,host="localhost",port=514,facility=Facility.DAEMON):
    self.host = host
    self.port = port
    self.facility = facility
    self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  def connect(self):
    try:
        self.socket.connect((self.host, self.port))
    except Exception as e:
        print("failed setting up connection")


  def send(self, message,level):
    data = "<%d>%s" % (level + self.facility*8, message + "\n")
    try:
        self.socket.sendall(data.encode('utf-8'))
    except Exception as e:
        print("send failed")

#if __name__ == '__main__':
syslog1 = Syslog(host='HOSTIPADDRESS-NAME')
syslog1.connect()
messages = ["test1","test2","test3","test4","test5","test6","test7"]

for message in messages:
    syslog1.send(message,Level.WARNING)

这工作得很好,当syslog服务器意外关闭时会遇到异常。我在调试时发现的唯一问题是:

当我关闭syslog服务器时,当我尝试发送消息时,它不会立即抛出异常。你知道吗

请参见下面的示例:

1.)syslog服务器启动后,我从for循环发送第一条消息“test1”,successfull。你知道吗

2.)我关闭了syslog服务器,现在我从for循环发送第二条消息“test2”。什么都没发生,也不例外!你知道吗

3.)我发送了第三条消息“test3”,现在抛出了一个异常。你知道吗

这怎么可能?你知道吗

相关问题 更多 >