【发布时间】:2016-10-04 15:50:10
【问题描述】:
看了Python的日志模块的handlers.py,发现轮换日志的逻辑不合理。下图是它的cmets:
我认为这种逻辑是不合理的,尤其是在 Windows 中:如果其他一些进程持有日志文件的处理程序,那么重命名将失败。例如,我有两个进程,一个进程发现是时候轮换文件了,所以它关闭了自己的处理程序并重命名了日志。但这一次,日志文件的处理程序被另一个进程持有,因此将引发 IO 异常,因为现在无法重命名日志文件。这就是为什么我们说日志模块在多进程中是不安全的。
我的问题是:为什么不直接创建另一个日志文件?为什么需要重命名日志文件?
假设日志名为console.log,我想逻辑应该是这样的:
if there is not console.log in destination folder:
create console.log and logging info
else:
add the suffix to the log file name.(e.g.: console.log.1)
create the file and logging info
if the log file gets filled up:
close the handler of the log file
increase the suffix number
create console.log.`newsuffix`(e.g.:console.log.2) and continue to logging info
在这个逻辑中,不需要重命名文件,所以不会引发IO Exception。
如果Python的日志模块的rotatingFileHandler使用我的逻辑,你能发现一些bug吗?
【问题讨论】: