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

标签 python http asynchronous logging

<分区>

我正在尝试实现简单的日志处理程序,它使用 Python 的标准 logging 库将事件记录到远程服务器。因此,我创建了继承自 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)

这按预期工作,但当 remote_url 变得不可访问或开始响应缓慢时,显然会导致调用线程锁定。因此,我试图找到使此调用独立于调用线程的最佳方法。

我的想法:

  1. 包括一些使 http 请求异步的非标准库
  2. 按照概述使用 QueueHandler 和 QueueListener here
  3. 使用异步

所有这些解决方案对于实现如此简单的任务来说似乎都过于复杂/不必要。是否有一些开销更少的更好方法来使该处理程序成为非阻塞的?

最佳答案

对于任何将要面对这个问题的人来说,解决方案就像描述的那样简单 here .

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()

QueueListener 在其自己的线程中运行并监听由 QueueHandlers 发送的 LogRecords,从而实现非阻塞日志记录。

关于python - 实现非阻塞远程日志处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46754062/

相关文章:

http - 不在 net/http golang 中处理 GET

node.js - 使用 cy.task 动态创建测试

jquery - 解除所有事件与通过 AJAX 动态添加的内容的绑定(bind)

python - 无法读取肯定存在的文件

python - 求解 C*M = N(C、M 和 N 是矩阵),其中 M 已知且 N 的结构在 SymPy 中给出

python - 我可以将安装在适用于 Linux 的 Windows 子系统上的 Redis 与 Windows 中的 python 应用程序一起使用吗?

javascript - 等待所有回调完成执行,没有静态时间

python - numpy.fromstring 中的 ValueError

http - 使用 Content-Type : application/octet-stream encoding overhead 通过 HTTP 的二进制数据

c# - StreamReader 缓冲带有 GZIP 的流式 HTTP?