|
|
|
@ -1,38 +0,0 @@
|
|
|
|
|
import os
|
|
|
|
|
import stat
|
|
|
|
|
import fcntl
|
|
|
|
|
import platform
|
|
|
|
|
from logging.handlers import RotatingFileHandler
|
|
|
|
|
|
|
|
|
|
class _MultiCompatibleRotatingFileHandler(RotatingFileHandler):
|
|
|
|
|
"""Inherit RotatingFileHandler for multiprocess compatibility.
|
|
|
|
|
|
|
|
|
|
这个类继承自`RotatingFileHandler`,是为了在多进程环境下安全地使用日志回滚功能。
|
|
|
|
|
在多进程环境下,多个进程可能会同时尝试写入或回滚日志文件,这可能会导致文件损坏或数据丢失。
|
|
|
|
|
通过在这个类中对相关方法进行重写,确保了日志文件在多进程环境下的正确处理。
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def doRollover(self):
|
|
|
|
|
"""Override doRollover for multiprocess compatibility
|
|
|
|
|
and setting permission of Log file
|
|
|
|
|
|
|
|
|
|
这个方法重写了`RotatingFileHandler`中的`doRollover`方法,增加了多进程兼容性,
|
|
|
|
|
并设置了日志文件的权限。
|
|
|
|
|
|
|
|
|
|
1. 使用`fcntl`模块获得独占锁,确保在回滚日志文件时不会有其他进程进行写操作。
|
|
|
|
|
2. 设置日志文件的权限,以确保日志文件的安全性。
|
|
|
|
|
3. 调用父类的`doRollover`方法执行实际的日志回滚操作。
|
|
|
|
|
4. 回滚后,修改日志文件的权限,使其可读可写。
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
# Attain an exclusive lock with blocking mode by `fcntl` module.
|
|
|
|
|
with open(self.baseFilename, 'a') as file_pointer:
|
|
|
|
|
# 如果操作系统不是Windows,使用`fcntl`模块对文件加锁
|
|
|
|
|
if platform.system() != "Windows":
|
|
|
|
|
fcntl.lockf(file_pointer.fileno(), fcntl.LOCK_EX)
|
|
|
|
|
# 设置日志文件权限为只读,增加安全性
|
|
|
|
|
os.chmod(self.baseFilename, stat.S_IREAD)
|
|
|
|
|
# 调用父类的`doRollover`方法执行日志回滚操作
|
|
|
|
|
super().doRollover()
|
|
|
|
|
# 修改日志文件的权限为可读可写,以便后续的日志写入操作
|
|
|
|
|
os.chmod(self.baseFilename, stat.S_IREAD | stat.S_IWRITE)
|