python - 为什么python日志记录RotatingFileHandler在多个进程中使用时会丢失记录?

标签 python logging multiprocessing

最近我发现我的应用程序生成的日志记录比我预期的要少。经过一些实验,我发现问题出在 RotatingFileHandler 和多处理中。

import logging
from logging import handlers
from multiprocessing import Pool
import os


log_file_name = 'log.txt'
def make_logger():
    logger = logging.getLogger('my_logger')
    logger.setLevel(logging.INFO)

    current_handler_names = {handler.name for handler in logger.handlers}
    handler_name = 'my_handler'
    if handler_name in current_handler_names:
        return logger

    handler = handlers.RotatingFileHandler(
        log_file_name, maxBytes=10 * 2 ** 10, backupCount=0)
    handler.setLevel(logging.INFO)
    handler.set_name(handler_name)

    logger.addHandler(handler)

    return logger



def f(x):
    logger = make_logger()
    logger.info('hey %s' % x)


if os.path.exists(log_file_name):
    os.unlink(log_file_name)

p = Pool(processes=30)
N = 1000
p.map(f, range(N))
with open(log_file_name, 'r') as f:
    print 'expected: %s, real: %s' % (N, f.read().count('hey'))

输出:

$ python main.py
expected: 1000, real: 943

我做错了什么?

最佳答案

原样well explained ,

Although logging is thread-safe, and logging to a single file from multiple threads in a single process is supported, logging to a single file from multiple processes is not supported

简而言之,RotatingFileHandler 只是关闭并删除一个进程中的文件,然后打开一个新文件。但是其他进程不知道新的文件描述符并且看到之前的文件描述符已经关闭。只有首先成功旋转文件的进程才会继续记录。

my answer对于类似的问题,我建议使用 logrotate 守护进程将文件旋转到这些进程之外。它不会关闭文件描述符,而只是截断文件。因此文件保持不变,其他进程可以继续记录。

关于python - 为什么python日志记录RotatingFileHandler在多个进程中使用时会丢失记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48660849/

相关文章:

python - Pandas 按列分组和排序,需要添加逗号分隔的条目

python - 遍历字典并按顺序打印其值

Python 一般数字格式化行为

Python 多进程终止进程

python - 用于多处理的共享内存中的大型 numpy 数组 : Is something wrong with this approach?

python - Pandas 改变数据帧结构

logging - 以 "realtime"的速度重播日志文件?

java - 如何为记录器生成实例?

Python正则表达式如何找到以给定单词开头并以两个单词之一结尾的子字符串

python - 初始化分布式工作人员的状态