如何在rotatingfilehandler中监视文件名更改?

2024-10-06 14:21:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用gunicorn运行我的flask应用程序的2进程。 我使用filerotatingfilehandler来旋转日志文件。 问题是当一个进程旋转日志文件时,另一个进程不知道,然后它旋转文件(现在命名为日志.txt(1)再次日志.txt.2,可能会改变日志.txt至日志.txt.1)。然后一个进程登录日志.txt其他人登录时日志.txt.1. 我知道我可以使用watchedfilehandler+logrotate来解决这个问题。 但是我仍然可以使用rotatingfilehandler并检测文件名的更改吗?你知道吗


Tags: 文件txt应用程序flask进程文件名命名gunicorn
1条回答
网友
1楼 · 发布于 2024-10-06 14:21:10

可以使用分布式全局锁来防止双重旋转,如this example gist。你知道吗

不过,我建议您在Flask应用程序中使用WatchedFileHandler

from celery.signals import after_setup_logger
from logging import ERROR, Formatter
from logging.handlers import WatchedFileHandler
from yourapp import app


LOG_FORMAT = (
    '-' * 80 + '\n' +
    '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +
    '%(message)s\n' +
    '-' * 80
)


if not app.config['DEBUG']:
    error_handler = WatchedFileHandler(app.config['ERROR_HANDLER_LOG'], delay=True)
    error_handler.setFormatter(Formatter(LOG_FORMAT))
    error_handler.setLevel(ERROR)

    @after_setup_logger.connect
    def after_setup_logger(logger, *args, **kwargs):
        logger.addHandler(error_handler)

    @app.before_first_request
    def before_first_request():
        app.logger.addHandler(error_handler)

然后使用cron脚本或文件监视守护程序通过重命名日志文件来旋转日志文件。你知道吗

相关问题 更多 >