溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python多進(jìn)程下中如何實(shí)現(xiàn)日志記錄按時間分割

發(fā)布時間:2021-06-03 11:33:39 來源:億速云 閱讀:333 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)python多進(jìn)程下中如何實(shí)現(xiàn)日志記錄按時間分割,小編覺得挺實(shí)用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

python多進(jìn)程下實(shí)現(xiàn)日志記錄按時間分割,供大家參考,具體內(nèi)容如下

原理:自定義日志handler繼承TimedRotatingFileHandler,并重寫computeRollover與doRollover函數(shù)。其中重寫computeRollover是為了能按整分鐘/小時/天來分割日志,如按天分割,2018-04-10 00:00:00~2018-04-11 00:00:00,是一個半閉半開區(qū)間,且不是原意的:從日志創(chuàng)建時間或當(dāng)前時間開始,到明天的這個時候。

代碼如下:

#!/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))
    # 修改內(nèi)容--開始
    # 在多進(jìn)程下,若發(fā)現(xiàn)dfn已經(jīng)存在,則表示已經(jīng)有其他進(jìn)程將日志文件按時間切割了,只需重新打開新的日志文件,寫入當(dāng)前日志;
    # 若dfn不存在,則將當(dāng)前日志文件重命名,并打開新的日志文件
    if not os.path.exists(dfn):
      try:
        self.rotate(self.baseFilename, dfn)
      except FileNotFoundError:
        # 這里會出異常:未找到日志文件,原因是其他進(jìn)程對該日志文件重命名了,忽略即可,當(dāng)前日志不會丟失
        pass
    # 修改內(nèi)容--結(jié)束
    # 原內(nèi)容如下:
    """
    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

說明

第一次修改,如有不妥之處,還請指出,不勝感激。

關(guān)于“python多進(jìn)程下中如何實(shí)現(xiàn)日志記錄按時間分割”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI