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中实现的RC4算法
Feb 14 Python
Python可跨平台实现获取按键的方法
Mar 05 Python
OPENCV去除小连通区域,去除孔洞的实例讲解
Jun 21 Python
在python中按照特定顺序访问字典的方法详解
Dec 14 Python
Django2.1集成xadmin管理后台所遇到的错误集锦(填坑)
Dec 20 Python
python读取各种文件数据方法解析
Dec 29 Python
详解opencv Python特征检测及K-最近邻匹配
Jan 21 Python
python获取Linux发行版名称
Aug 30 Python
python图像处理模块Pillow的学习详解
Oct 09 Python
解决python replace函数替换无效问题
Jan 18 Python
Python脚本去除文件的只读性操作
Mar 05 Python
详解如何修改jupyter notebook的默认目录和默认浏览器
Jan 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防止form重复提交的方法
2013/07/01 PHP
php生成动态验证码gif图片
2015/10/19 PHP
Yii2下session跨域名共存的解决方案
2017/02/04 PHP
Laravel5.0+框架邮件发送功能实现方法图文与实例详解
2019/04/23 PHP
清空上传控件input file的值
2010/07/03 Javascript
腾讯的ip接口 方便获取当前用户的ip地理位置
2010/11/25 Javascript
JQuery获取样式中的background-color颜色值的问题
2013/08/20 Javascript
jquery实现div阴影效果示例代码
2013/09/16 Javascript
javascript中的undefined和not defined区别示例介绍
2014/02/26 Javascript
jquery实现无限分级横向导航菜单的方法
2015/03/12 Javascript
原生js实现模拟滚动条
2015/06/15 Javascript
NodeJS 实现手机短信验证模块阿里大于功能
2017/06/19 NodeJs
微信小程序中this.data与this.setData的区别详解
2018/09/17 Javascript
Vue组件之单向数据流的解决方法
2018/11/10 Javascript
highCharts提示框中显示当前时间的方法
2019/01/18 Javascript
原生js实现的移动端可拖动进度条插件功能详解
2019/08/15 Javascript
[03:09]DOTA2亚洲邀请赛 LGD战队出场宣传片
2015/02/07 DOTA
[04:42]2015国际邀请赛CDEC战队晋级之路
2015/08/13 DOTA
简明 Python 基础学习教程
2007/02/08 Python
python实现的希尔排序算法实例
2015/07/01 Python
Python实现递归遍历文件夹并删除文件
2016/04/18 Python
Python中%r和%s的详解及区别
2017/03/16 Python
老生常谈Python基础之字符编码
2017/06/14 Python
Python简单实现自动删除目录下空文件夹的方法
2017/08/29 Python
Python Flask上下文管理机制实例解析
2020/03/16 Python
python爬虫爬取某网站视频的示例代码
2021/02/20 Python
利用CSS3制作简单的3d半透明立方体图片展示
2017/03/25 HTML / CSS
巴西男士胡须和头发护理产品商店:Beard
2017/11/13 全球购物
PacSun官网:加州生活方式服装、鞋子和配饰
2018/03/10 全球购物
Crabtree & Evelyn英国官网:瑰珀翠护手霜、香水、沐浴和身体护理
2018/04/26 全球购物
大专毕业生简历的自我评价
2013/10/20 职场文书
QA工程师岗位职责
2013/11/20 职场文书
庆国庆活动总结
2014/08/28 职场文书
2016寒假社会实践心得体会范文
2015/10/09 职场文书
python实现过滤敏感词
2021/05/08 Python
Python+Matplotlib图像上指定坐标的位置添加文本标签与注释
2022/04/11 Python