在运行系统代码时,我需要记录大量数据。有哪些日志记录包可以使用以实现高效的异步日志记录? Python 的标准日志记录包(https://docs.python.org/2/library/logging.html)默认是异步的吗?
在运行系统代码时,我需要记录大量数据。有哪些日志记录包可以使用以实现高效的异步日志记录? Python 的标准日志记录包(https://docs.python.org/2/library/logging.html)默认是异步的吗?
您可以使用一组n工作者,使用concurrent.futures.ThreadPoolExecutor执行logging.info()
信息,其中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)
异步代码可以使用常规的日志记录功能,而无需借助特殊的异步模块或包装器。这样的代码是可能的。
import logging
async def do_some_async_stuff(self):
logging.getLogger(__name__).info("Started doing stuff...")
logging.getLogger(__name__).warn("Things went awry...")
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()
然后使用所需的日志条目格式配置嵌套在监听器中的处理程序。
我个人喜欢旋转文件处理程序,因为它限制了产生的日志文件的大小和数量,在创建新备份时删除最旧的文件。
emit
方法。 - Pynchia$ pip install polog
from polog import log, config, file_writer
config.add_handlers(file_writer('file.log')) # Add a file handler.
config.set(pool_size=2) # The size of the thread pool. By default it's 0, that means "not asynchronous".
log('message')