2014-09-02 106 views
2

我還沒有完全掌握足夠的Python來解決這個問題,所以我在尋求幫助。使用變量設置日誌記錄級別

我有各種日誌消息分散在我的python模塊中。我想在代碼中調用該模塊能夠通過這樣設置調試級別:

module.DEBUG = INFO

例如。但我無法將其轉化爲工作。我有全局變量「調試」,我想它在下面的行進行解釋,而不是DEBUG充當文本字符串,這是我認爲正在發生的事情:

logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.DEBUG) 

我怎樣才能使該字符串被視爲一個變量而不是文字(如果這就是發生了什麼?)

謝謝!

--Matt

+0

調試是一個級別。我想你的意思是說你想設置日誌級別 – Elisha 2014-09-02 19:39:49

+0

logging.DEBUG不是字面的。它是一個整數。 ('logging.DEBUG == 10') – Elisha 2014-09-02 19:41:56

回答

4

如果你想調用代碼控制模塊上的日誌記錄級別,你應該考慮接受日誌級別爲你的模塊中的一個參數。下面是你如何做到這一點的一些示例代碼:

import logging 

class MyModule(object): 
""" 
Sample module to demonstrate setting of loglevel on init 
""" 

    def __init__(self, logLevel): 
     #logLevel, a string, should be one of the levels of the logging modules. Example: DEBUG, INFO, WARNING etc. 

     #Translate the logLevel input string to one of the accepted values of the logging module. Change it to upper to allow calling module to use lowercase 
     #If it doesn't translate default to something like DEBUG which is 10 
     numeric_level = getattr(logging, logLevel.upper(), 10) 

     logging.basicConfig(filename='example.log', level=numeric_level) 


    def testLogger(self): 
     #logging object that you defined the level in init is used here for some sample logging 
     logging.debug('see this at debug level') 
     logging.info('see this at info and debug') 
     logging.warning('see this at warn, info and debug') 


if __name__ == "__main__": 
    MM= MyModule('info') 
    MM.testLogger()