如何在超过maxBytes到当前datetime.log后重命名将在rotateFileHandler中创建的日志文件?

时间:2017-06-05 00:47:32

标签: python python-2.7

是否可以覆盖rotateFileHandler的rollOver(),以便日志文件名称为当前日期time.log?

我是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)

1 个答案:

答案 0 :(得分:0)

这是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 = "%s\n" % 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

这是我们有记录器功能的.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')

总体而言,此程序会根据天数,小时数和分钟数从指定路径中删除日志文件。并创建名为current datetime.log的日志文件,如果日志文件超过10 mb,则会创建名为current datetime.log的其他日志文件。