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判断操作系统类型代码分享
Nov 22 Python
python简单获取数组元素个数的方法
Jul 13 Python
Windows下为Python安装Matplotlib模块
Nov 06 Python
Python 通过URL打开图片实例详解
Jun 01 Python
Python 3.6 性能测试框架Locust安装及使用方法(详解)
Oct 11 Python
Python 实现域名解析为ip的方法
Feb 14 Python
创建Django项目图文实例详解
Jun 06 Python
python关于调用函数外的变量实例
Dec 26 Python
Pytorch 之修改Tensor部分值方式
Dec 27 Python
Python&amp;&amp;GDAL实现NDVI的计算方式
Jan 09 Python
python实现电子词典
Mar 03 Python
教你使用Python获取QQ音乐某个歌手的歌单
Apr 03 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 php_openssl.dll的作用
2013/07/01 PHP
ThinkPHP实现将本地文件打包成zip下载
2014/06/26 PHP
php中使用gd库实现远程图片下载实例
2015/05/12 PHP
php去除二维数组的重复项方法
2015/11/03 PHP
PHP使用socket发送HTTP请求的方法
2016/02/14 PHP
php版微信小店调用api示例代码
2016/11/12 PHP
PHP模型Model类封装数据库操作示例
2019/03/14 PHP
CentOS7系统搭建LAMP及更新PHP版本操作详解
2020/03/26 PHP
JavaScript可否多线程? 深入理解JavaScript定时机制
2012/05/23 Javascript
从零学jquery之如何使用回调函数
2014/05/16 Javascript
第二篇Bootstrap起步
2016/06/21 Javascript
Bootstrap select实现下拉框多选效果
2016/12/23 Javascript
jQuery自定义插件详解及实例代码
2016/12/29 Javascript
浅谈在vue中用webpack打包之后运行文件的问题以及相关配置方法
2018/02/21 Javascript
浅析Vue项目中使用keep-Alive步骤
2018/07/27 Javascript
vue prop属性传值与传引用示例
2019/11/13 Javascript
原生JavaScript创建不可变对象的方法简单示例
2020/05/07 Javascript
Python的另外几种语言实现
2015/01/29 Python
Python下的常用下载安装工具pip的安装方法
2015/11/13 Python
python flask实现分页效果
2017/06/27 Python
Python基于回溯法子集树模板解决旅行商问题(TSP)实例
2017/09/05 Python
Python Series从0开始索引的方法
2018/11/06 Python
使用python批量化音乐文件格式转换的实例
2019/01/09 Python
python导入坐标点的具体操作
2019/05/10 Python
windows中安装Python3.8.0的实现方法
2019/11/19 Python
Python综合应用名片管理系统案例详解
2020/01/03 Python
Python写捕鱼达人的游戏实现
2020/03/31 Python
查找适用于matplotlib的中文字体名称与实际文件名对应关系的方法
2021/01/05 Python
橄榄树药房:OLIVEDA
2019/09/01 全球购物
新闻专业推荐信范文
2013/11/20 职场文书
协议书与合同的区别
2014/04/18 职场文书
党的群众路线教育实践活动学习笔记
2014/11/05 职场文书
农村党员干部承诺书
2015/05/04 职场文书
2016中秋节广告语
2016/01/28 职场文书
MySQL慢查询的坑
2021/04/28 MySQL
Golang 并发编程 SingleFlight模式
2022/04/26 Golang