如何重命名将在超过当前dateTime.log的maxbytes之后将在旋转filehandler中创建的日志文件



是否有可能覆盖旋转filehandler的滚动((,以便日志文件名称为当前日期时间?

我是Python编程的新手。

代码:

def logger(self , inputStr):
    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')
    fileName = 'log-'+dateTime+'.log'
    Path = path+'/'+fileName
    logger = logging.getLogger("Rotating Log")
    logger.setLevel(logging.DEBUG)
    #logger = logging.Formatter('%(asctime)-15s %(clientip)s %(user)-8s %(message)s')         
    handler = RotatingFileHandler(Path, maxBytes=1000000, backupCount=5)
    logger.addHandler(handler)
    for i in range(1000000):
        logger.debug("This is test log line %s" % i)

这就是dorollover((被覆盖以将备份文件名作为当前dateTime.log myrotatingfilehandler.py

import datetime 
import os
import sys
import logging
from logging.handlers import BaseRotatingHandler
import time
class myRotatingFileHandler(BaseRotatingHandler):
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):
    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')
    filename = filename +'/log-'+dateTime+'.log'
    if maxBytes > 0:
        mode = 'a'
    BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
    self.maxBytes = maxBytes
    self.backupCount = backupCount
def doRollover(self):
    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')
    #fileName = 'log-'+dateTime+'.log'
    df = ''
    if self.stream:
        self.stream.close()
        self.stream = None
    if self.backupCount > 0:
        for i in range(self.backupCount - 1, 0, -1):
            sf = self.baseFilename+'/'+'log-'+ datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S') + '.log'
            df = self.baseFilename+'/'+'log-'+ datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S') + '.log'
            if os.path.exists(sf):
                if os.path.exists(df):
                    os.remove(df)
                os.rename(sf, df)
        wkspFldr = os.path.dirname(self.baseFilename)
        df = wkspFldr+'/'+'log-'+ datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S') + '.log'
        print 'LOG FILE ---> ',df
        if os.path.exists(df):
            os.remove(df)
        if os.path.exists(self.baseFilename):
            os.rename(self.baseFilename, df)
    if not self.delay:
        self.stream = self._open()
def shouldRollover(self, record):
    if self.stream is None:                 
        self.stream = self._open()
    if self.maxBytes > 0:                   
        msg = "%sn" % self.format(record)
        self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature
        if self.stream.tell() + len(msg) >= self.maxBytes:
            return 1
    return 0

这是我们具有logger函数的.py代码 config.py

import logging
import os
import datetime
from logging.handlers import RotatingFileHandler
import time
from subprocess import call
from time import gmtime, strftime
import re
import logging.handlers
import myRotatingFileHandler
path = ''
Interval = ''
Value = 0
class config:
def __init__(self, givenPath, interval, value):
    global path
    global Interval
    global Value
    path = givenPath
    Interval = interval
    Value = value
def remove_file_by_days(self):
    now = time.time()
    cutoff = now - (value * 86400)
    files = os.listdir(path)
    file_path = os.path.join(path)
    for xfile in files:
        filePath = file_path + xfile
        if os.path.isfile(filePath):
            t = os.stat(filePath)
            c = t.st_ctime
            if c < cutoff:
                print 'removing file...'
                print filePath
                os.remove(filePath)
def remove_file_by_hours(self):
    dir_to_search = os.listdir(path)
    for file in filenames:
        curpath = os.path.join(path, file)
        file_modified = datetime.fromtimestamp(os.path.getmtime(curpath))
        if datetime.datetime.now() - file_modified > datetime.timedelta(hours = Value):
            print 'removing file...'
            print curpath
            os.remove(curpath)
def remove_file_by_minutes(self):
    dir_to_search = os.listdir(path)
    for file in dir_to_search:
        curpath = os.path.join(path, file)
        file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
        if datetime.datetime.now() - file_modified > datetime.timedelta(hours = Value/60 ):
            print 'removing file...'
            print curpath
            os.remove(curpath)
def logger(self , inputStr):
    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')
    fileName = 'log-'+dateTime+'.log'
    Path = path
    logger = logging.getLogger("Rotating Log")
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler = myRotatingFileHandler.myRotatingFileHandler(Path, maxBytes=1024000*10, backupCount=5)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    for i in range(1000000):
        logger.debug("This is test log line %s" % i)
def debug(self, inputStr):
    if Interval == 'days':
        self.remove_file_by_days()
    if Interval == 'hours':
        self.remove_file_by_hours()
    if Interval == 'minutes':
        self.remove_file_by_minutes()
    self.logger(inputStr)

通话主 logmain.py

import logging
import os
import sys
import config
from config import config
if __name__ == '__main__':
obj = config('/var/www/cgi-bin/pythonPractice/test/','minutes', 2)
obj.debug('abc')

总体而言,该程序确实根据日期,小时数和分钟数删除日志文件形成给定路径。并使用名称当前dateTime.log创建日志文件,如果日志文件超过10 MB,它将创建其他日志文件,并使用名称current dateTime.log。

最新更新