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求解平方根的方法
Mar 11 Python
详解Python中for循环的使用
Apr 14 Python
Python对数据库操作
Mar 28 Python
SQLite3中文编码 Python的实现
Jan 11 Python
Django视图之ORM数据库查询操作API的实例
Oct 27 Python
浅谈numpy数组的几种排序方式
Dec 15 Python
详解Python中如何写控制台进度条的整理
Mar 07 Python
Python实现基于TCP UDP协议的IPv4 IPv6模式客户端和服务端功能示例
Mar 22 Python
python生成任意频率正弦波方式
Feb 25 Python
浅析Python 条件控制语句
Jul 15 Python
如何利用python读取micaps文件详解
Oct 18 Python
解决Pytorch dataloader时报错每个tensor维度不一样的问题
May 28 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
一些操作和快捷键的理解和讨论
2020/03/04 星际争霸
PHP在XP下IIS和Apache2服务器上的安装
2006/09/05 PHP
dedecms模版制作使用方法
2007/04/03 PHP
PHP数组内存耗用太多问题的解决方法
2010/04/05 PHP
PHP基础教程(php入门基础教程)一些code代码
2013/01/06 PHP
WebQQ最新登陆协议的用法
2014/12/22 PHP
Laravel学习基础之migrate的使用教程
2017/10/11 PHP
PHP 断点续传实例详解
2017/11/11 PHP
微信公众平台开发教程④ ThinkPHP框架下微信支付功能图文详解
2019/04/10 PHP
C#中TrimStart,TrimEnd,Trim在javascript上的实现
2011/01/17 Javascript
jQuery代码优化 遍历篇
2011/11/01 Javascript
ExtJS4 表格的嵌套 rowExpander应用
2014/05/02 Javascript
jQuery向父辈遍历的简单方法
2016/09/18 Javascript
php输出全部gb2312编码内的汉字方法
2017/03/04 Javascript
vue swipe自定义组件实现轮播效果
2019/07/03 Javascript
[02:12]2019完美世界全国高校联赛(春季赛)报名开启
2019/03/01 DOTA
20招让你的Python飞起来!
2016/09/27 Python
Python处理PDF及生成多层PDF实例代码
2017/04/24 Python
Python基于递归算法实现的走迷宫问题
2017/08/04 Python
Python实现的概率分布运算操作示例
2017/08/14 Python
pandas中Timestamp类用法详解
2017/12/11 Python
python3 读写文件换行符的方法
2018/04/09 Python
python 通过类中一个方法获取另一个方法变量的实例
2019/01/22 Python
Python参数传递及收集机制原理解析
2020/06/05 Python
使用AJAX和Django获取数据的方法实例
2020/10/25 Python
西安夏日科技有限公司Java笔试题
2013/01/11 面试题
医学专业毕业生推荐信
2013/11/14 职场文书
初中毕业生的自我评价
2014/03/03 职场文书
幼儿园家长寄语
2014/04/02 职场文书
财务会计大学生自我评价
2014/04/09 职场文书
乡镇综治宣传月活动总结
2014/07/02 职场文书
创先争优公开承诺书
2014/08/30 职场文书
英语自我介绍演讲稿
2014/09/01 职场文书
机关副主任个人四风问题整改措施
2014/09/26 职场文书
《认识钟表》教学反思
2016/02/16 职场文书
yolov5返回坐标的方法实例
2022/03/17 Python