在运行系统代码时,我需要记录大量数据。我可以使用哪些日志记录包来实现高效的异步日志记录?默认情况下,标准Python日志记录包(https://docs.python.org/2/library/logging.html)是异步的吗?
发布于 2017-08-23 22:49:01
您可以使用n个worker池执行logging.info()消息,使用concurrent.futures.ThreadPoolExecutor,n应始终等于1:
import concurrent.futures
import logging
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
def info(self, msg, *args):
executor.submit(logging.info, msg, *args)发布于 2022-01-14 20:13:57
异步代码可以使用通常的日志记录功能,而无需借助特殊的异步模块或包装器。像这样的代码是可能的。
import logging
:
async def do_some_async_stuff(self):
logging.getLogger(__name__).info("Started doing stuff...")
:
logging.getLogger(__name__).warn("Things went awry...")这里要关注的是,在将日志条目写入文件时,提交日志条目是否会导致一些延迟,从而剥夺异步系统在失效期间运行其他任务的机会。如果将写入文件的阻塞处理程序直接添加到日志记录层次结构中的某个位置,就会发生这种情况。
标准logging模块为此提供了一个简单的解决方案:使用非阻塞处理程序,该处理程序将其消息排队到在其自己的私有线程中运行的所需的阻塞处理程序。
抛开纯粹主义不谈,没有硬绑定规则来排除使用QueueHandler来提供带有非阻塞日志处理程序的异步代码,该非阻塞日志处理程序与QueueListener中托管的阻塞处理程序一起使用。
下面的解决方案与调用logging记录器并以典型方式提交条目的协程完全兼容-不需要调用.run_in_executor()的包装器。异步代码不会遇到来自日志记录系统的任何阻塞行为。
例如,可以将QueueHandler设置为根处理程序
import queue
from logging.handlers import QueueHandler
:
log_queue = queue.Queue()
queue_handler = QueueHandler(log_queue) # Non-blocking handler.
root = logging.getLogger()
root.addHandler(queue_handler) # Attached to the root logger.并且您想要的阻塞处理程序可以放在QueueListener中
from logging.handlers import QueueListener
from logging.handlers import RotatingFileHandler
:
rot_handler = RotatingFileHandler(...) # The blocking handler.
queue_listener = QueueListener(log_queue,
rot_handler) # Sitting comfortably in its
# own thread, isolated from
# async code.
queue_listener.start()然后,使用所需的任何日志条目格式配置嵌套在侦听器中的处理程序。
我个人喜欢旋转文件处理程序,因为它限制了生成的日志文件的大小和数量,在创建新备份时删除最旧的日志文件。
https://stackoverflow.com/questions/45842926
复制相似问题