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 相关文章推荐
django基础之数据库操作方法(详解)
May 24 Python
利用python实现xml与数据库读取转换的方法
Jun 17 Python
彻底理解Python list切片原理
Oct 27 Python
Python3实现购物车功能
Apr 18 Python
Python创建普通菜单示例【基于win32ui模块】
May 09 Python
Python操作word常见方法示例【win32com与docx模块】
Jul 17 Python
Django框架视图函数设计示例
Jul 29 Python
python ctypes库2_指定参数类型和返回类型详解
Nov 19 Python
PIL.Image.open和cv2.imread的比较与相互转换的方法
Jun 03 Python
Python3中FuzzyWuzzy库实例用法
Nov 18 Python
Django-simple-captcha验证码包使用方法详解
Nov 28 Python
yolov5返回坐标的方法实例
Mar 17 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下获取上个月、下个月、本月的日期(strtotime,date)
2014/02/02 PHP
php构造函数的继承方法
2015/02/09 PHP
php删除文本文件中重复行的方法
2015/04/28 PHP
Redis在Laravel项目中的应用实例详解
2017/08/11 PHP
用window.location.href实现刷新另个框架页面
2007/03/07 Javascript
基于jQuery的仿flash的广告轮播代码
2010/11/04 Javascript
JavaScript面向对象之Prototypes和继承
2012/07/12 Javascript
uploadify在Firefox下丢失session问题的解决方法
2013/08/07 Javascript
jquery复选框全选/取消示例
2013/12/30 Javascript
基于NodeJS的前后端分离的思考与实践(四)安全问题解决方案
2014/09/26 NodeJs
JavaScript中反正弦函数Math.asin()的使用简介
2015/06/14 Javascript
JavaScript学习笔记整理_关于表达式和语句
2016/09/19 Javascript
JavaScript实现设置默认日期范围为最近40天的方法分析
2017/07/12 Javascript
JavaScript学习笔记之数组基本操作示例
2019/01/09 Javascript
解决vue-cli webpack打包开启Gzip 报错问题
2019/07/24 Javascript
vscode 调试 node.js的方法步骤
2020/09/15 Javascript
[46:59]完美世界DOTA2联赛PWL S2 GXR vs Ink 第二场 11.19
2020/11/20 DOTA
Python调用C语言开发的共享库方法实例
2015/03/18 Python
Python爬虫之pandas基本安装与使用方法示例
2018/08/08 Python
详解django中使用定时任务的方法
2018/09/27 Python
python2.7 安装pip的方法步骤(管用)
2019/05/05 Python
python基于Selenium的web自动化框架
2019/07/14 Python
用python写测试数据文件过程解析
2019/09/25 Python
Python3操作读写CSV文件使用包过程解析
2020/04/10 Python
Python变量及数据类型用法原理汇总
2020/08/06 Python
详解WebSocket跨域问题解决
2018/08/06 HTML / CSS
英国最大的经认证的有机超市:Planet Organic
2018/02/02 全球购物
全球最大的游戏市场:G2A
2018/07/05 全球购物
创联软件面试题笔试题
2012/10/07 面试题
应聘面试自我评价
2014/01/24 职场文书
元旦晚会邀请函
2014/02/01 职场文书
优良学风班总结材料
2014/02/08 职场文书
人事专员职责
2014/02/22 职场文书
2014年学生会工作总结
2014/11/07 职场文书
小学数学新课改心得体会
2016/01/22 职场文书
幼儿园音乐教学反思
2016/02/18 职场文书