2011-10-19 16 views
2

fileconfigでロギングを使用し、プログラム設定でロギングするかどうかによって、Pythonロギングの動作が異なることがわかりました。Pythonのロギング:fileconfigとプログラム設定を使用したときの動作が異なる

説明するために、2つの最小限の例を作成しました。

最初の例では、プログラムでロギングを設定しています。この例は正常に動作します。デバッグログメッセージはコンソールに出力されます。

# foo.py 
import logging 

logger = logging.getLogger(__name__) 

class Foo(object): 
    def __init__(self): 
     logger.debug('debug log from Foo') 

########################################################################## 
# loggingtest.py 
import logging.config 

from foo import Foo 

if __name__ == '__main__': 
    consoleLogger = logging.StreamHandler() 
    formatter = logging.Formatter(
     '%(asctime)-6s: %(name)s - %(levelname)s - %(message)s') 
    consoleLogger = logging.StreamHandler() 
    consoleLogger.setLevel(logging.DEBUG) 
    consoleLogger.setFormatter(formatter) 

    rootLogger = logging.getLogger() 
    rootLogger.addHandler(consoleLogger) 
    rootLogger.setLevel(logging.NOTSET) 
    # prints debug log message to console 
    foo = Foo() 

私の2番目の例では、fileConfigでログを設定しています。私が見る限り、log-config-fileはまったく同じ動作をする必要があります。しかし、この例では、デバッグログメッセージは表示されません。

# foo.py (same as above) 
import logging 

logger = logging.getLogger(__name__) 

class Foo(object): 
    def __init__(self): 
     logger.debug('debug log from Foo') 
########################################################################## 
# loggingtest.py 
import logging.config 

from foo import Foo 

if __name__ == '__main__': 
    logging.config.fileConfig('logging.cfg')  

    # does NOT print debug log message to console. WHY??? 
    foo = Foo() 

########################################################################## 
# logging.cfg 
[loggers] 
keys = root 

[logger_root] 
level = NOTSET 
handlers = consoleHandler 

[formatters] 
keys = complex 

[formatter_complex] 
format = %(asctime)s - %(name)s - %(levelname)s - %(module)s : %(lineno)d - %(message)s 

[handlers] 
keys = consoleHandler 

[handler_consoleHandler] 
class=StreamHandler 
level=DEBUG 
formatter=complex 
args=(sys.stdout,) 

なぜ、2番目の例では、logging fileconfigを使用して、デバッグログメッセージをコンソールに出力しないのですか?

答えて

6

fileConfigは、デフォルトでは、既存のロガーを無効にしているので、

from foo import Foo 

または

logging.config.fileConfig("logging.cfg",disable_existing_loggers=0) 
を呼び出す前に

logging.config.fileConfig("logging.cfg") 

を呼び出します

関連する問題