Skip to main content
 首页 » 编程设计

python之需要使用 Python 进行每日日志轮换(0utc)

2025年05月04日8xiaohuochai

我是 Python 的公认新手。我写了一个小记录器,它从串行端口获取数据并将其写入日志文件。我有一个小程序可以打开文件进行追加、写入,然后关闭。我怀疑这可能不是最好的方法,但这是我到目前为止想到的。

我希望能够让它在 00 UTC 自动执行日志轮换,但到目前为止,我尝试使用 RotatingFileHandler 执行此操作都失败了。

代码如下:

import time, serial, logging, logging.handlers,os,sys 
from datetime import * 
 
CT12 = serial.Serial() 
CT12.port = "/dev/ct12k" 
CT12.baudrate = 2400 
CT12.parity = 'E' 
CT12.bytesize = 7 
CT12.stopbits = 1 
CT12.timeout = 3 
 
logStart = datetime.now() 
dtg = datetime.strftime(logStart, '%Y-%m-%d %H:%M:%S ') 
ctlA = unichr(1) 
bom = unichr(2) 
eom = unichr(3) 
bel = unichr(7) 
CT12Name = [ctlA, 'CT12-NWC-test'] 
CT12Header = ['-Ceilometer Logfile \r\n', '-File created: ', dtg, '\r\n'] 
 
def write_ceilo ( text ) : 
    f = open ('/data/CT12.log', 'a') 
    f.write (text) 
    f.close () 
 
write_ceilo(''.join(CT12Header)) 
 
CT12.open() 
 
discard = CT12.readlines() 
#print (discard) 
 
while CT12.isOpen(): 
    response = CT12.readline() 
    if len(response) >= 3: 
        if response[0] == '\x02' : 
            now=datetime.now() 
            dtg=datetime.strftime(now, '-%Y-%m-%d %H:%M:%S\r\n') 
            write_ceilo(dtg) 
            write_ceilo(''.join(CT12Name)) 
            write_ceilo(response) 

我该怎么做才能使它自动轮换,并附上轮换日期或序列号以供识别。我不打算轮换其中任何一个,只是保留数据的每日日志文件。 (或者可能是每小时文件?)

请您参考如下方法:

对于通过 Google 到达的任何人,请不要在记录器正在使用时通过调用移动命令等系统副本将日志文件从记录器中移出。

您正在寻找的是 TimedRotatingFileHandler :

import time 
 
import logging 
from logging.handlers import TimedRotatingFileHandler 
 
# format the log entries 
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s') 
 
handler = TimedRotatingFileHandler('/path/to/logfile.log',  
                                   when='midnight', 
                                   backupCount=10) 
handler.setFormatter(formatter) 
logger = logging.getLogger(__name__) 
logger.addHandler(handler) 
logger.setLevel(logging.DEBUG) 
 
# generate example messages 
for i in range(10000): 
    time.sleep(1) 
    logger.debug('debug message') 
    logger.info('informational message') 
    logger.warn('warning') 
    logger.error('error message') 
    logger.critical('critical failure')