Merge "Add time based rotating log file handler"
This commit is contained in:
commit
6b539f0e85
56
libra/common/logging_handler.py
Normal file
56
libra/common/logging_handler.py
Normal file
@ -0,0 +1,56 @@
|
||||
# Copyright 2012 Hewlett-Packard Development Company, L.P.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import gzip
|
||||
import os
|
||||
import time
|
||||
import glob
|
||||
import codecs
|
||||
|
||||
|
||||
class CompressedTimedRotatingFileHandler(
|
||||
logging.handlers.TimedRotatingFileHandler
|
||||
):
|
||||
def doRollover(self):
|
||||
self.stream.close()
|
||||
t = self.rolloverAt - self.interval
|
||||
timeTuple = time.localtime(t)
|
||||
tfn = '{0}.{1}'.format(
|
||||
self.baseFilename, time.strftime(self.suffix, timeTuple)
|
||||
)
|
||||
if os.path.exists(tfn):
|
||||
os.remove(tfn)
|
||||
os.rename(self.baseFilename, tfn)
|
||||
# Delete oldest log
|
||||
# TODO: clear multiple old logs
|
||||
if self.backupCount > 0:
|
||||
s = glob.glob('{0}.20'.format(self.baseFilename))
|
||||
if len(s) > self.backupCount:
|
||||
s.sort()
|
||||
os.remove(s[0])
|
||||
if self.encoding:
|
||||
self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
|
||||
else:
|
||||
self.stream = open(self.baseFilename, 'w')
|
||||
self.rolloverAt = self.rolloverAt + self.interval
|
||||
zfile = '{0}.gz'.format(tfn)
|
||||
if os.path.exists(zfile):
|
||||
os.remove(zfile)
|
||||
f_in = open(tfn, "rb")
|
||||
f_out = gzip.open(zfile, "wb")
|
||||
f_out.writelines(f_in)
|
||||
f_out.close()
|
||||
f_in.close()
|
||||
os.remove(tfn)
|
@ -19,7 +19,7 @@ import sys
|
||||
import ConfigParser
|
||||
|
||||
from libra import __version__
|
||||
|
||||
from logging_handler import CompressedTimedRotatingFileHandler
|
||||
|
||||
"""
|
||||
Common options parser.
|
||||
@ -178,7 +178,9 @@ def setup_logging(name, args):
|
||||
)
|
||||
|
||||
if logfile:
|
||||
handler = logging.FileHandler(logfile)
|
||||
handler = CompressedTimedRotatingFileHandler(
|
||||
logfile, when='D', interval=1, backupCount=7
|
||||
)
|
||||
handler.setFormatter(ts_formatter)
|
||||
else:
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
|
Loading…
x
Reference in New Issue
Block a user