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

作者:Just_Walking 时间:2022-10-07 21:00:24 

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

说明

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

来源:https://blog.csdn.net/Just_Walking/article/details/79877346

标签:python,日志分割
0
投稿

猜你喜欢

  • Python3爬虫之urllib携带cookie爬取网页的方法

    2022-07-01 14:19:02
  • python Copula 实现绘制散点模型

    2023-07-24 14:02:37
  • 剖析SQL Server 事务日志的收缩和截断

    2009-01-15 13:04:00
  • mysql 5.7 docker 主从复制架构搭建教程

    2024-01-21 22:46:03
  • php多任务程序实例解析

    2023-11-18 00:22:09
  • 详解CentOS 6.5中安装mysql 5.7.16 linux glibc2.5 x86 64(推荐)

    2024-01-15 19:01:11
  • 解决python 读取npy文件太大不能完全显示的问题

    2021-08-20 12:07:19
  • 利用python实现数据分析

    2023-01-05 22:07:27
  • 如何用python开发Zeroc Ice应用

    2022-06-23 01:17:50
  • 详解Golang实现http重定向https的方式

    2024-05-09 09:47:02
  • pycharm下配置pyqt5的教程(anaconda虚拟环境下+tensorflow)

    2021-07-02 16:53:41
  • MySQL实战窗口函数SQL分析班级学生考试成绩及生活消费

    2024-01-15 08:56:14
  • 利用MySqlBulkLoader实现批量插入数据的示例详解

    2024-01-24 08:46:00
  • JavaScript实现时钟滴答声效果

    2024-04-16 10:38:19
  • Python列表和集合的效率大比拼

    2021-09-04 14:10:16
  • php以post形式发送xml的方法

    2023-11-22 12:40:47
  • Django ORM 多表查询示例代码

    2021-07-25 05:22:02
  • mysql prompt的用法详解

    2024-01-28 07:30:32
  • 关于useSSL=false和true的区别及说明

    2024-01-25 03:27:40
  • SQL SERVER 2012新增函数之逻辑函数CHOOSE详解

    2024-01-15 10:04:06
  • asp之家 网络编程 m.aspxhome.com