2015-10-22 96 views
0

嗨我想在python上啓用日誌,由於某些原因沒有記錄。有人能幫我解決我犯的錯誤嗎?Python日誌記錄自定義處理程序和格式化程序沒有被記錄

def setup(): 
    logger = logging.getLogger('mytest') 
    formatter = logging.Formatter('%(asctime)s %(message)s') 

    fileHandler = logging.FileHandler('mylog.log') 
    fileHandler.setLevel(logging.DEBUG) 
    fileHandler.setFormatter(formatter) 

    logger.addHandler(fileHandler) 
    logger.debug('hello world') 
+0

您需要對'logger'變量調用'setLevel' – kmad1729

回答

0

下面的例子會使它更清楚一點。您需要設置的主要級別是logger對象。您可以通過調用getEffectiveLevel方法來檢查logger級別。

def setup(): 
    logger = logging.getLogger('mytest') 
    formatter = logging.Formatter('%(asctime)s %(message)s') 
    fileHandler = logging.FileHandler('mylog.log') 
    fileHandler.setLevel(logging.DEBUG) 
    fileHandler.setFormatter(formatter) 
    logger.addHandler(fileHandler) 

    logger.critical("before setting Level on logger, effective level = {}".format(
      logger.getEffectiveLevel())) 


    #THIS WON'T BE logged becuse logger level is WARN 
    # and DEBUG < WARN 
    logger.debug('logging debug before setting debug level') 

    logger.setLevel(logging.DEBUG) 

    logger.critical("after setting Level on logger, effective level = {}".format(
      logger.getEffectiveLevel())) 


    #THIS WILL BE logged in mylog.log because DEBUG >= DEBUG 
    logger.debug('logging debug after setting debug level') 

    fileHandler.setLevel(logging.CRITICAL) 


    #THIS WON'T BE logged in mylog.log because fileHandler level is CRITICAL---> 
    # and DEBUG < CRITICAL 
    logger.debug("this won't be printed in mylog.log") 


    #THIS WILL BE logged in mylog.log BECAUSE CRITICAL >= CRITICAL---> 
    logger.critical("logging at critical level") 
相關問題