带有TimedRotatingFileHandler后缀的Python Daily记录器

时间:2012-10-23 23:25:40

标签: python logging python-2.6

我是Python和编程的新手,我正在尝试制作一个简单的日常记录器。我想使用TimedRotatingFileHandler因为它符合我的需要,虽然我不能改变后缀,这是重要的。我将需要我的日志使用“.csv”扩展名。 所以我找到了一个类MyTimedRotatingFileHandler,它应该添加后缀但不幸的是,我没有得到我犯错的地方。

以下是我正在尝试实现的代码,由几个从网络上获取的代码段组成。

# -*- coding: utf-8 -*-
import serial
import os
import time
import logging
from logging.handlers import TimedRotatingFileHandler

ser = serial.Serial('/dev/ttyACM0', 38400, timeout=15)

class MyTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
  def __init__(self,dir_log):
  self.dir_log = dir_log
  filename =  self.dir_log+time.strftime("%m%d%Y")+".csv"
  logging.handlers.TimedRotatingFileHandler.__init__(self,filename, 
                        when='S', interval=5, backupCount=0, encoding=None)

def doRollover(self):

   line = ser.readline()
   self.baseFilename = self.dir_log+time.strftime("%d/%m/%Y %H:%M:%S")+".csv"
   self.stream = open(self.baseFilename, 'w')
   self.rolloverAt = self.rolloverAt + self.interval
   a="%s,%s,%s,%s" % (self.baseFileName,'Température :',line,"\n")
#a =  "{0},{1},{2},{3}".format(self.baseFileName,'Température :',line,"\n")
print a 
self.info(a)
#    logger.flush()
ser.close()

1 个答案:

答案 0 :(得分:1)

您的缩进似乎不正确,因为selfself.info(a)中未定义。您应该缩进doRollOver,因此它是MyTimedRotatingFileHandler的方法然后实例化该类在某处,调用该方法并检查print a是否按预期工作。