python - logging.handler.TimedRotatingFileHandler never rotates the log -
a have script synchronizes time on linux servers( centos 6) , writes offset in log. want make after 10 days current log (ntp.log) copy old (ntp.log-date), not work. script continues write 1 file , not rotating. run cron every 5 minutes. using python version 2.6. set interval in seconds check. doing wrong?
#!/usr/bin/env python import ntplib import logging logging.handlers import timedrotatingfilehandler time import ctime import os import socket hostname = socket.gethostname() loghandler = timedrotatingfilehandler('/root/ntp/log/ntp.log', when='s', interval=300) logformatter = logging.formatter('%(asctime)s %(message)s', datefmt='%d/%m/%y %h:%m:%s') loghandler.setformatter(logformatter) logger = logging.getlogger('mylogger') logger.addhandler(loghandler) logger.setlevel(logging.info) c = ntplib.ntpclient() response = c.request('1.rhel.pool.ntp.org') logger.info('| %s time offset | %s' % (hostname, response.offset)) datestr = ctime(response.tx_time) os.system('date -s "%s"' % datestr)
leaving outside fact algorithm plain incorrect, i'll answer question regarding logging issue.
here's related logging.handlers.timedrotatingfilehandler
logic:
def __init__(<...>): <...> if self.when == 's': self.interval = 1 # 1 second <...> self.interval = self.interval * interval # multiply units requested <...> if os.path.exists(filename): t = os.stat(filename)[st_mtime] else: t = int(time.time()) self.rolloverat = self.computerollover(t) def computerollover(self, currenttime): result = currenttime + self.interval <special logic doesn't apply in case> return result
so, rollover time in 's'
mode computed file's mtime @ time of script's init. mtime modified each time write file.
thus, rollover done if log after interval
seconds since script's start. never case since runs less.
possible fixes:
- make script run long, e.g. infinite loop suggested. if it's run indefinitely, should made daemon
- change rollover moment calculation algorithm
- this not possible stock logic (the "special logic" in
timedrotatingfilehandler.computerollover()
applies'midnight'
,'wn'
cases), need replace handler'scomputerollover()
- basically, need set rollover time next "reference moment" after current file's mtime.
- this not possible stock logic (the "special logic" in
Comments
Post a Comment