用 Python 写一个多进程兼容的 TimedRotatingFileHandler
我前面有篇文章已经详细介绍了一下 Python 的日志模块。Python 提供了非常多的可以运用在各种不同场景的 Log Handler.
TimedRotatingFileHandler 是 Python 提供的一个可以基于时间自动切分日志的 Handler 类,他继承自 BaseRotatingHandler -> logging.FileHandler
但是他有一个缺点就是没有办法支持多进程的日志切换,多进程进行日志切换的时候可能会因为重命名而丢失日志数据。
来看下他的实现(我默认大家已经知道了 FileHandler 的实现和 logging 模块的调用机制 如果还不清楚可以先去看下我前面那篇文章 https://www.cnblogs.com/piperck/p/9634133.html):
def doRollover(self):
"""
do a rollover; in this case, a date/time stamp is appended to the filename
when the rollover happens. However, you want the file to be named for the
start of the interval, not the current time. If there is a backup count,
then we have to get a list of matching filenames, sort them and remove
the one with the oldest suffix.
"""
if self.stream:
self.stream.close()
self.stream = None
# get the time that this sequence started at and make it a TimeTuple
currentTime = int(time.time())
dstNow = time.localtime(currentTime)[-1]
t = self.rolloverAt - self.interval
if self.utc:
timeTuple = time.gmtime(t)
else:
timeTuple = time.localtime(t)
dstThen = timeTuple[-1]
if dstNow != dstThen:
if dstNow:
addend = 3600
else:
addend = -3600
timeTuple = time.localtime(t + addend)
dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
if os.path.exists(dfn):
os.remove(dfn)
# Issue 18940: A file may not have been created if delay is True.
if os.path.exists(self.baseFilename):
os.rename(self.baseFilename, dfn)
if self.backupCount > 0:
for s in self.getFilesToDelete():
os.remove(s)
if not self.delay:
self.stream = self._open()
newRolloverAt = self.computeRollover(currentTime)
while newRolloverAt <= currentTime:
newRolloverAt = newRolloverAt + self.interval
#If DST changes and midnight or weekly rollover, adjust for this.
if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
dstAtRollover = time.localtime(newRolloverAt)[-1]
if dstNow != dstAtRollover:
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
addend = -3600
else: # DST bows out before next rollover, so we need to add an hour
addend = 3600
newRolloverAt += addend
self.rolloverAt = newRolloverAt
doRollover 其实就是 rotate 的具体实现。在具体详细分析为什么会出现多进程问题的时候我先来说下 rotate 的原理。
首先日志会被打印在一个叫 baseFilename 名字的文件中。然后在 Rotate 的时候会根据你想要打印的参数生成对应新文件的名字也就是上面函数的 dfn 的值。
然后会将现在的文件重命名为 dfn 的值。之后在重新创建一个 baseFilename 的文件。然后继续往这个文件里面写。
举个例子,我们一直往 info.log 中写日志。现在该 rotate 了我们会把 info.log rename 成 info.log.2018-10-23 然后再创建一个 info.log 继续写日志,过程就是这样。
让我们来注意导致多进程问题的最关键的几句话:
if os.path.exists(dfn):
os.remove(dfn)
# Issue 18940: A file may not have been created if delay is True.
if os.path.exists(self.baseFilename):
os.rename(self.baseFilename, dfn)
我们就根据上面的例子继续来描述。比如现在 dfn 就是 info.log.2018-10-23 。那么我会看有没有存在这个文件,如果有我就会先删除掉,然后再看下 info.log 是否存在,如果存在就执行 rename.
所以问题就很明确了,如果同时有多个进程进入临界区,那么会导致 dfn 文件被删除多次,另外下面的 rename 可能也会产生混乱。
现在我们要做的就是首先认为文件存在即是已经有人 rename 成功过了,并且在判断文件不存在的时候只允许一个人去 rename ,其他进程如果正好进入临界区就等一等。
让我们来实现这个函数:
class MultiCompatibleTimedRotatingFileHandler(TimedRotatingFileHandler): def doRollover(self):
if self.stream:
self.stream.close()
self.stream = None
# get the time that this sequence started at and make it a TimeTuple
currentTime = int(time.time())
dstNow = time.localtime(currentTime)[-1]
t = self.rolloverAt - self.interval
if self.utc:
timeTuple = time.gmtime(t)
else:
timeTuple = time.localtime(t)
dstThen = timeTuple[-1]
if dstNow != dstThen:
if dstNow:
addend = 3600
else:
addend = -3600
timeTuple = time.localtime(t + addend)
dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
# 兼容多进程并发 LOG_ROTATE
if not os.path.exists(dfn):
f = open(self.baseFilename, 'a')
fcntl.lockf(f.fileno(), fcntl.LOCK_EX)
if not os.path.exists(dfn):
os.rename(self.baseFilename, dfn)
# 释放锁 释放老 log 句柄
f.close()
if self.backupCount > 0:
for s in self.getFilesToDelete():
os.remove(s)
if not self.delay:
self.stream = self._open()
newRolloverAt = self.computeRollover(currentTime)
while newRolloverAt <= currentTime:
newRolloverAt = newRolloverAt + self.interval
# If DST changes and midnight or weekly rollover, adjust for this.
if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
dstAtRollover = time.localtime(newRolloverAt)[-1]
if dstNow != dstAtRollover:
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
addend = -3600
else: # DST bows out before next rollover, so we need to add an hour
addend = 3600
newRolloverAt += addend
self.rolloverAt = newRolloverAt
我们判断一下如果该文件不存在,我们就进入临界区,然后利用 linux 的 fcntl 用阻塞模式获得一把文件锁。然后判断一下 info.log 是否已经被 rename 过了(这里用于同时进入临界区的其他进程判断前面持锁人是否已经结束完成了文件的 rename)。如果文件还在说明是第一个进来的进程则执行 rename 操作。将 info.log -> info.log.2018-10-23 。完成了之后这个时候 info.log 就已经暂时不存在于当前目录了。而且 dfn 文件已经创建。所以后面进来的进程会跳过这个判断直接执行下面的逻辑 open 一个新的基于 self.baseFilename 的文件。这里同时打开就无所谓了,因为 FileHandler 默认使用的 mode 是 'a' appending 模式,所以当 open 的时候就不会存在覆盖的情况了。
到此就补偿了无法兼容多进程的问题。这里还想多提一句,在写这个的时候经过了很长时间对 fcntl 模块的调研。他是一个基于 linux 的 voluntary 锁。也就是说是一把自愿锁。虽然我在调用的时候加了强制排它锁,但是其他不自愿的比如我再开一个 vim 去编辑该文件是可以绕过这个锁的这个一定要注意。
Reference:
https://gavv.github.io/blog/file-locks/ File locking in Linux
https://www.cnblogs.com/gide/p/6811927.html python中给程序加锁之fcntl模块的使用
http://blog.jobbole.com/104331/ Linux 中 fcntl()、lockf、flock 的区别
用 Python 写一个多进程兼容的 TimedRotatingFileHandler的更多相关文章
- 用Python写一个简单的Web框架
一.概述 二.从demo_app开始 三.WSGI中的application 四.区分URL 五.重构 1.正则匹配URL 2.DRY 3.抽象出框架 六.参考 一.概述 在Python中,WSGI( ...
- 十行代码--用python写一个USB病毒 (知乎 DeepWeaver)
昨天在上厕所的时候突发奇想,当你把usb插进去的时候,能不能自动执行usb上的程序.查了一下,发现只有windows上可以,具体的大家也可以搜索(搜索关键词usb autorun)到.但是,如果我想, ...
- [py]python写一个通讯录step by step V3.0
python写一个通讯录step by step V3.0 参考: http://blog.51cto.com/lovelace/1631831 更新功能: 数据库进行数据存入和读取操作 字典配合函数 ...
- 【Python】如何基于Python写一个TCP反向连接后门
首发安全客 如何基于Python写一个TCP反向连接后门 https://www.anquanke.com/post/id/92401 0x0 介绍 在Linux系统做未授权测试,我们须准备一个安全的 ...
- Python写一个自动点餐程序
Python写一个自动点餐程序 为什么要写这个 公司现在用meican作为点餐渠道,每天规定的时间是早7:00-9:40点餐,有时候我经常容易忘记,或者是在地铁/公交上没办法点餐,所以总是没饭吃,只有 ...
- 用python写一个自动化盲注脚本
前言 当我们进行SQL注入攻击时,当发现无法进行union注入或者报错等注入,那么,就需要考虑盲注了,当我们进行盲注时,需要通过页面的反馈(布尔盲注)或者相应时间(时间盲注),来一个字符一个字符的进行 ...
- python写一个能变身电光耗子的贪吃蛇
python写一个不同的贪吃蛇 写这篇文章是因为最近课太多,没有精力去挖洞,记录一下学习中的收获,python那么好玩就写一个大一没有完成的贪吃蛇(主要还是跟课程有关o(╥﹏╥)o,课太多好烦) 第一 ...
- python写一个邮箱伪造脚本
前言: 原本打算学php MVC的思路然后写一个项目.但是贼恶心, 写不出来.然后就还是用python写了个邮箱伪造. 0x01 第一步先去搜狐注册一个邮箱 然后,点开设置,开启SMTP服务. 当然你 ...
- 用python写一个非常简单的QQ轰炸机
闲的没事,就想写一个QQ轰炸机,按照我最初的想法,这程序要根据我输入的QQ号进行轰炸,网上搜了一下,发现网上的案列略复杂,就想着自己写一个算了.. 思路:所谓轰炸机,就是给某个人发很多信息,一直刷屏, ...
随机推荐
- P1913 L国的战斗之伞兵(广搜BFS)
就是在输入的时候把 ‘o’ 的放在队里,然后,直接BFS就可以了.感觉是水题. #include<iostream> #include<queue> using namespa ...
- Y7000 (1)安装ubuntu1604遇到的问题
1安装系统 分区的时候 /boot 不再是引导分区 换成 “为系统bois保留的分区” 这个分区取代 /boot 2第一次进系统没有图形界面 在刚开机 ubuntu系统时 按e 在splash后面空 ...
- (二 -5) 天猫精灵接入Home Assistant-自动发现Mqtt设备--电风扇
官网:https://www.home-assistant.io/components/fan.mqtt/ 1 添加配置文件 要在安装中启用MQTT风扇,请将以下内容添加到您的configuratio ...
- Spring配置中的"classpath:"与"classpath*:"的区别研究(转)
Spring配置中的"classpath:"与"classpath*:"的区别研究(转) 概念解释及使用场景: classpath是指WEB-INF文件夹下 ...
- mysql 监控工具(windows版本)
文章转自 https://www.cnblogs.com/wucj/p/7152020.html 工具下载 http://www.profilesql.com/download/
- HTTP协议、HTTP请求方法、常见状态码、HTTP消息
HTTP协议 客户端请求,服务端响应.浏览器与服务器不建立持久连接,响应后连接失效. HTTP请求方法 一.GET GET方法用于获取请求页面的指定信息. 二.HEAD 除了服务器不能在响应里返回消息 ...
- Spring MVC自定义403,404,500状态码返回页面
代码 HTTP状态码干货:http://tool.oschina.net/commons?type=5 import org.springframework.boot.web.servlet.erro ...
- Ansible 简介
Ansible 是一个开源的基于 OpenSSH 的自动化配置管理工具.可以用它来配置系统.部署软件和编排更高级的 IT 任务,比如持续部署或零停机更新.Ansible 的主要目标是简单和易用,并且它 ...
- Java面试MySQL的一些问题
MySQL InnoDB存储的文件结构 索引树是如何维护的? 数据库自增主键可能的问题
- H5 20-属性选择器上
20-属性选择器上 --> 我是段落1 我是段落2 我是段落3 我是段落4 我是段落5 <!DOCTYPE html> <html lang="en"> ...