是否可以覆盖rotationFileHandler 的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)
这就是如何覆盖 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
这是我们有记录器功能config.py的 .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 的其他日志文件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句