2013-03-02 76 views
0

我有下面的類:Python記錄:只記錄到處理程序不剷除

class Log(object): 

# class new 
#new is used instead of init because __new__ is able to return (where __init__ can't) 
def __new__(self, name, consolelevel, filelevel): 

    formatter = logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s') 

    #Create consolehandler and set formatting (level is set in the ROOT) 
    consolehandler = StreamHandler() 
    consolehandler.setFormatter(formatter) 

    #Create filehandler, set level and set formatting 
    filehandler = FileHandler(name + '.log') 
    filehandler.setLevel(filelevel) 
    filehandler.setFormatter(formatter) 

    #Create the root logger, add console and file logger. Set the rootlevel == consolelevel. 
    self.root = logging.getLogger(name) 

    #causing me problems.... 
    self.root.setLevel(consolelevel) 

    self.root.addHandler(consolehandler) 
    self.root.addHandler(filehandler) 
    self.root.propagate = True 

    return self.root 

# Close the logger object 
def close(): 
    # to be implemented 
    pass 

我使用這個類來登錄到控制檯和文件(根據設定的水平)。問題在於,根級似乎是處理器的主角。有沒有辦法來禁用這個?現在我將rootlevel設置爲與consolelevel相同的級別,但這不起作用...

有什麼建議嗎?

預先感謝與問候,

JR

+0

「問題是根級別似乎是導致addhandlers。」這有*無*的含義。你的意思是記錄器增加了更多的處理程序,然後你的想法是什麼? – Bakuriu 2013-03-02 12:12:54

回答

1

一個問題,我可以在你的代碼中看到的是,每當你實例Log類會增加更多的處理器。你可能不想要這個。

請記住,使用相同的參數調用getLogger時總是返回相同的實例,基本上它實現了單例模式。 因此,當您稍後致電addHandler時,它會每次添加一個新的處理程序。

處理logging的方法是在模塊級創建一個記錄器並使用它。

另外我會避免使用__new__。在你的情況下,你可以使用一個簡單的功能。並且請注意,您的Log.close方法不會工作,因爲您的__new__方法不會返回Log實例,因此返回的記錄器不具有該方法。

關於記錄器的級別,我不明白你爲什麼不在consolehandler上設置級別,而是在整個記錄器上。

+0

好的,所以可能我使用了錯誤的方法。 – 2013-03-02 13:42:26

+0

好的,所以可能我使用了錯誤的方法。我有一個有幾個類的模塊。我希望能夠爲每個班級設置一個單獨的日誌模塊。我希望能夠爲每個類設置獨立的控制檯和文件級別。什麼是最好的方法來使用? – 2013-03-02 13:47:47

+0

我稍後會發布一些代碼(因爲我沒有足夠的聲譽...)來說明 – 2013-03-02 14:15:17

0

這是我製作的模塊的簡化版本。該模塊包含一些需要記錄功能的類。每個類都記錄到不同的文件,並且還應該可以更改類之間的文件處理程序級別(例如,遊戲手柄類:console.debug和filehandler.info以及MQTT類:控制檯信息和filehandler.debug)。

因此,我認爲設置日誌類是最簡單的方法。請記住,我通常做電子產品,但現在與python結合。所以,我的技能是非常基本的....

#!/bin/env python2.7 

未來進口部 從運營商進口* 進口記錄 從伐木進口StreamHandler中 進口pygame的進口記錄的FileHandler 進口從pygame的線程 。當地人導入* 進口mosquitto 進口時間 不時進口睡眠 進口SYS

類ConsoleFileLogger(對象):

# class constructor 
def __init__(self, filename, loggername, rootlevel, consolelevel, filelevel): 

    # logger levels: DEBUG, INFO, WARNING, ERROR, CRITICAL 

    # define a root logger and set its ROOT logging level 
    logger = logging.getLogger(loggername) 
    logger.setLevel(rootlevel) 

    # define a Handler which writes messages or higher to the sys.stderr (Console) 
    self.console = logging.StreamHandler() 
    # set the logging level 
    self.console.setLevel(consolelevel) 

    # define a Handler which writes messages to a logfile 
    self.logfile = logging.FileHandler(filename + '.log') 
    # set the logging level 
    self.logfile.setLevel(filelevel) 

    # create formatter and add it to the handlers 
    formatter = logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s') 
    self.console.setFormatter(formatter) 
    self.logfile.setFormatter(formatter) 

    # add the handlers to the root logger 
    logger.addHandler(self.console) 
    logger.addHandler(self.logfile) 

    self._logger = logger 

# set a net instance of the logger 
def set(self): 
    return self._logger 

# Stop and remove the ConsoleFileLogger object 
def remove(self): 
    self._logger.removeHandler(self.console) 
    self._logger.removeHandler(self.logfile) 
    self._logfile.FileHandler().close() 

類遊戲手柄():

# class constructor 
def __init__(self, mqttgamepad): 
    self.logger = ConsoleFileLogger('BaseLogFiles/Gamepad', 'Gamepad', logging.INFO, logging.INFO, logging.INFO).set() 

    if joystickcount == 0: 
     self.logger.error('No gamepad connected') 
    elif joystickcount == 1: 
     self.gamepad = pygame.joystick.Joystick(0) 
     self.gamepad.init() 
     self.logger.debug('Joystick name %s', self.gamepad.get_name()) 
     self.logger.debug('nb of axes = %s', self.gamepad.get_numaxes()) 
     self.logger.debug('nb of balls = %s', self.gamepad.get_numballs()) 
     self.logger.debug('nb of buttons = %s', self.gamepad.get_numbuttons()) 
     self.logger.debug('nb of mini joysticks = %s', self.gamepad.get_numhats()) 
    elif joystickcount > 1: 
     self.logger.error('only one gamepad is allowed') 

def run(self): 
    self.logger.debug('gamepad running') 

類MQTTClient() :

def __init__(self, clientname): 
    self.logger = ConsoleFileLogger('BaseLogFiles/MQTT/Pub', clientname, logging.DEBUG, logging.DEBUG, logging.DEBUG).set() 
    self.logger.debug('test') 

def run(self): 
     self.logger.info('Connection MQTT Sub OK') 

DEF主(): 記錄器= ConsoleFileLogger( 'BaseLogFiles/logControlCenterMain', 'ControlCenterMain',logging.DEBUG,logging.DEBUG,logging.DEBUG).SET()

mqttclient = MQTTClient("MQTTClient") 
mqttclient.connect() 

gamepad = Gamepad(mqttclient) 

if gamepad.initialized(): 
    gamepadthread = threading.Thread(target=gamepad.run) 
    gamepadthread.start() 

    mqtttpubhread = threading.Thread(target=mqttclient.run) 
    mqtttpubhread.start() 

logger.info('BaseMain started') 

# Monitor the running program for a KeyboardInterrupt exception 
# If this is the case all threads and other methods can be closed the correct way :) 
while 1: 
    try: 
     sleep(1) 
    except KeyboardInterrupt: 
     logger.info('Ctrl-C pressed') 
     gamepad.stop() 
     mqttclient.stop() 
     logger.info('BaseMain stopped') 
     sys.exit(0) 

如果名稱 = ='main': main()

+0

任何人有一些想法?我真的不知道如何繼續。謝謝 – 2013-03-03 09:51:55

相關問題