有一个脚本可以同步linux服务器上的时间(CentOS 6)并在日志中写入偏移量。我想在10天后将当前日志(ntp.log)复制到旧(ntp.log-date),但这不起作用。该脚本继续写入一个文件而不是旋转。它由cron每5分钟运行一次。我使用python 2.6版。我特意设置了检查的间隔(秒)。我究竟做错了什么?
#!/usr/bin/env python
import ntplib
import logging
from logging.handlers import TimedRotatingFileHandler
from 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 is | %s' % (hostname, response.offset))
datestr = ctime(response.tx_time)
os.system('date -s "%s"' % datestr)
答案 0 :(得分:1)
除了您的算法明显不正确之外,我将回答有关记录问题的问题。
这是相关的logging.handlers.TimedRotatingFileHandler
逻辑:
def __init__(<...>):
<...>
if self.when == 'S':
self.interval = 1 # one second
<...>
self.interval = self.interval * interval # multiply by 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 that doesn't apply in your case>
return result
因此,'S'
模式下的翻转时间是在脚本初始化时从文件mtime计算出来的。每次写入文件时都会修改 mtime 。
因此,只有在脚本开始后interval
秒之后进行记录,才会进行翻转。从来没有这种情况,因为它运行的次数要少得多。
可能的修复:
TimedRotatingFileHandler.computeRollover()
仅适用于'MIDNIGHT'
和'Wn'
个案例),因此您需要更换你的经纪人computeRollover()
答案 1 :(得分:0)
这可能对您有所帮助(如果日志以第 10 天的倍数创建并且日志上次修改是前一天,则滚动日志)
#!/usr/bin/env python
import ntplib
import logging
from logging.handlers import TimedRotatingFileHandler
from time import ctime
import os
import socket
hostname = socket.gethostname()
logHandler = TimedRotatingFileHandler('/root/ntp/log/ntp.log', when='D', interval=10)
logFormatter = logging.Formatter('%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S')
logHandler.setFormatter(logFormatter)
#Get File creation Time
log_ctime = datetime.fromtimestamp(os.path.getctime("/root/ntp/log/ntp.log")).date()
log_mtime = datetime.fromtimestamp(os.path.getmtime("/root/ntp/log/ntp.log")).date()
delta_c = datetime.now().date() - log_ctime
delta_m = datetime.now().date() - log_mtime
if delta_c.days %10 == 0 and delta_m.days>=1:
logHandler.doRollover()
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 is | %s' % (hostname, response.offset))
datestr = ctime(response.tx_time)
os.system('date -s "%s"' % datestr)