python多进程下实现日志记录按时间分割


Posted in Python onJuly 22, 2019

python多进程下实现日志记录按时间分割,供大家参考,具体内容如下

原理:自定义日志handler继承TimedRotatingFileHandler,并重写computeRollover与doRollover函数。其中重写computeRollover是为了能按整分钟/小时/天来分割日志,如按天分割,2018-04-10 00:00:00~2018-04-11 00:00:00,是一个半闭半开区间,且不是原意的:从日志创建时间或当前时间开始,到明天的这个时候。

代码如下:

#!/usr/bin/env python
# encoding: utf-8

"""自定义日志处理类"""


import os
import time
from logging.handlers import TimedRotatingFileHandler


class MyLoggingHandler(TimedRotatingFileHandler):

  def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None):
    TimedRotatingFileHandler.__init__(self, filename, when=when, interval=interval, backupCount=backupCount, encoding=encoding, delay=delay, utc=utc, atTime=atTime)

  def computeRollover(self, currentTime):
    # 将时间取整
    t_str = time.strftime(self.suffix, time.localtime(currentTime))
    t = time.mktime(time.strptime(t_str, self.suffix))
    return TimedRotatingFileHandler.computeRollover(self, t)

  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.rotation_filename(self.baseFilename + "." +
                   time.strftime(self.suffix, timeTuple))
    # 修改内容--开始
    # 在多进程下,若发现dfn已经存在,则表示已经有其他进程将日志文件按时间切割了,只需重新打开新的日志文件,写入当前日志;
    # 若dfn不存在,则将当前日志文件重命名,并打开新的日志文件
    if not os.path.exists(dfn):
      try:
        self.rotate(self.baseFilename, dfn)
      except FileNotFoundError:
        # 这里会出异常:未找到日志文件,原因是其他进程对该日志文件重命名了,忽略即可,当前日志不会丢失
        pass
    # 修改内容--结束
    # 原内容如下:
    """
    if os.path.exists(dfn):
      os.remove(dfn)
    self.rotate(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

说明

第一次修改,如有不妥之处,还请指出,不胜感激。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现对一个完整url进行分割的方法
Apr 29 Python
python urllib爬取百度云连接的实例代码
Jun 19 Python
Python读取txt某几列绘图的方法
Oct 14 Python
Python socket实现多对多全双工通信的方法
Feb 13 Python
pyqt5 comboBox获得下标、文本和事件选中函数的方法
Jun 14 Python
VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的方法详解
Jul 01 Python
python监控进程状态,记录重启时间及进程号的实例
Jul 15 Python
Python 、Pycharm、Anaconda三者的区别与联系、安装过程及注意事项
Oct 11 Python
Pytorch Tensor 输出为txt和mat格式方式
Jan 03 Python
python模拟预测一下新型冠状病毒肺炎的数据
Feb 01 Python
Pandas —— resample()重采样和asfreq()频度转换方式
Feb 26 Python
利用PyTorch实现VGG16教程
Jun 24 Python
Django框架自定义模型管理器与元选项用法分析
Jul 22 #Python
python实现日志按天分割
Jul 22 #Python
python re.sub()替换正则的匹配内容方法
Jul 22 #Python
简单了解python gevent 协程使用及作用
Jul 22 #Python
利用Pandas和Numpy按时间戳将数据以Groupby方式分组
Jul 22 #Python
python+logging+yaml实现日志分割
Jul 22 #Python
python删除列表元素的三种方法(remove,pop,del)
Jul 22 #Python
You might like
用PHP发电子邮件
2006/10/09 PHP
php+mysql实现无限级分类 | 树型显示分类关系
2006/11/19 PHP
php zend解密软件绿色版测试可用
2008/04/14 PHP
《PHP编程最快明白》第二讲 数字、浮点、布尔型、字符串和数组
2010/11/01 PHP
php连接Access数据库错误及解决方法
2013/06/20 PHP
使用php语句将数据库*.sql文件导入数据库
2014/05/05 PHP
PHP生成树的方法
2015/07/28 PHP
php cli模式下获取参数的方法
2017/05/05 PHP
确保Laravel网站不会被嵌入到其他站点中的方法
2019/10/18 PHP
jquery仿百度经验滑动切换浏览效果
2015/04/14 Javascript
AngularJS教程之MVC体系结构详解
2016/08/16 Javascript
浅析Node.js:DNS模块的使用
2016/11/23 Javascript
简单实现js选项卡切换效果
2017/02/09 Javascript
js 动态生成html 触发事件传参字符转义的实例
2017/02/14 Javascript
浅析vue中常见循环遍历指令的使用 v-for
2018/04/18 Javascript
浅析vue插槽和作用域插槽的理解
2019/04/22 Javascript
后台使用freeMarker和前端使用vue的方法及遇到的问题
2019/06/13 Javascript
微信小程序中网络请求缓存的解决方法
2019/12/29 Javascript
[48:38]DOTA2亚洲邀请赛 3.31 小组赛 B组 Mineski vs Secret
2018/03/31 DOTA
python通过scapy获取局域网所有主机mac地址示例
2014/05/04 Python
Windows下为Python安装Matplotlib模块
2015/11/06 Python
python 统计一个列表当中的每一个元素出现了多少次的方法
2018/11/14 Python
PyQt5实现五子棋游戏(人机对弈)
2020/03/24 Python
详解python深浅拷贝区别
2019/06/24 Python
django重新生成数据库中的某张表方法
2019/08/28 Python
基于Python 中函数的 收集参数 机制
2019/12/21 Python
Python爬虫headers处理及网络超时问题解决方案
2020/06/19 Python
详解Python 中的容器 collections
2020/08/17 Python
萌新的HTML5 入门指南
2020/11/06 HTML / CSS
装潢设计专业推荐信模板
2013/11/26 职场文书
海飞丝广告词
2014/03/20 职场文书
2015新年联欢晚会开场白
2014/12/14 职场文书
员工工作表现自我评价
2015/03/06 职场文书
年度考核表个人总结
2015/03/06 职场文书
Redis如何一键部署脚本
2021/04/12 Redis
吃通javascript正则表达式
2021/04/21 Javascript