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

Ger*_*ryC 1 python logging pyserial

我是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)
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能使其自动旋转,粘贴旋转日期或序列号,以便识别.我不打算将这些中的任何一个旋转出来,只保留数据的每日日志文件.(或者可能是每小时的文件?)

Zac*_*chP 9

对于通过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')
Run Code Online (Sandbox Code Playgroud)

  • 如果记录日志的 Python 代码或应用程序未连续运行,则不会运行。你知道一个解决方案吗? (2认同)