Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 实现非阻塞远程日志处理程序_Python_Http_Asynchronous_Logging - Fatal编程技术网

Python 实现非阻塞远程日志处理程序

Python 实现非阻塞远程日志处理程序,python,http,asynchronous,logging,Python,Http,Asynchronous,Logging,我试图实现一个简单的日志处理程序,它使用Python的标准日志记录库将事件记录到远程服务器。所以我创建了从logging.Handler继承的名为RemoteLogHandler的自定义类,该类接受LogRecord并将其发送到远程服务器。处理程序以标准的addHandler()方式连接到根记录器 from urllib import requests class RemoteLogHandler(logging.Handler): def emit(self, record):

我试图实现一个简单的日志处理程序,它使用Python的标准
日志记录
库将事件记录到远程服务器。所以我创建了从
logging.Handler
继承的名为
RemoteLogHandler
的自定义类,该类接受
LogRecord
并将其发送到远程服务器。处理程序以标准的
addHandler()
方式连接到根记录器

from urllib import requests

class RemoteLogHandler(logging.Handler):
    def emit(self, record):
        remote_url = "http://foo.bar.baz"
        req = request.Request(remote_url, data=record.msg)
        request.urlopen(req, timeout=1)
这可以按预期工作,但当远程url变得不可访问或开始响应缓慢时,显然会导致调用线程锁定。因此,我试图找出使这个调用独立于调用线程的最佳方法

我所考虑的是:

  • 包括一些使http请求异步的非标准库
  • 如所述使用QueueHandler和QueueListener
  • 使用asyncio

  • 对于完成如此简单的任务来说,所有这些解决方案似乎过于复杂/不必要。是否有一些开销更小的更好方法可以使该处理程序无阻塞?

    对于任何将要面对这一问题的人来说,解决方案正如所描述的那样简单


    QueueListener在其自己的线程中运行,并侦听QueueHandler发送的日志记录,这将导致非阻塞日志记录。

    您的应用程序不应将其日志路由到任何地方,请参见例如,为什么您认为队列解决方案是一种过度复杂化?这是这里唯一的解决方案:远程推送记录的工作线程,以及在发送记录时将记录添加到队列中的普通线程。您也可以切换到UDP通信,只需以非阻塞的方式发送数据报。但是不能保证远程交付和处理(syslog处理程序就是这样工作的,afaik)。
    import queue
    from logging.handlers import QueueHandler, QueueListener
    
    # instantiate queue & attach it to handler
    log_queue = queue.Queue(-1)
    queue_handler = QueueHandler(log_queue)
    
    # instantiate our custom log handler (see question)
    remote_handler = RemoteLogHandler()
    
    # instantiate listener
    remote_listener = QueueListener(log_queue, remote_handler)
    
    # attach custom handler to root logger
    logging.getLogger().addHandler(queue_handler)
    
    # start the listener
    remote_listener.start()