2015-10-16 16 views
2

我正在使用dictConfig來設置日誌記錄。我的要求之一是更改格式化程序的默認轉換器(我爲所有處理程序使用單個格式化程序simpleFormatter)至time.gmtime。這將完成like this如何在使用dictConfig時重新配置記錄器格式器

formatter.converter = time.gmtime 

如果我有權訪問格式化程序。但我沒有,所以我不能更改默認的轉換器。我能想到的做的兩種方式我想:

  • 通過dictConfig通過相關參數,在formatters部分(像'converter': 'ext://time.gmtime')但我認爲這額外的參數不是由dictConfig
  • 獲得支持格式化程序,然後執行dictConfig並手動應用配置:formatter.converter = time.gmtime。我不知道如何按名稱獲取格式化程序,或者是否支持該格式化程序,或者是否會在logging.config模塊中進行攻擊。

在查看日誌記錄模塊的源代碼後,我沒有找到任何示例,文檔,也沒有找到實現此方法的方法。

有人設法使用dictConfig安裝程序設置formatter.converter

回答

2

下面是如何做到這一點的例子:

import logging 
import logging.config 
import time 

class UTCFormatter(logging.Formatter): 
    converter = time.gmtime 

LOGGING = { 
    'version': 1, 
    'disable_existing_loggers': False, 
    'formatters': { 
     'utc': { 
      '()': UTCFormatter, 
      'format': '%(asctime)s %(message)s', 
     }, 
     'local': { 
      'format': '%(asctime)s %(message)s', 
     } 
    }, 
    'handlers': { 
     'console1': { 
      'class': 'logging.StreamHandler', 
      'formatter': 'utc', 
     }, 
     'console2': { 
      'class': 'logging.StreamHandler', 
      'formatter': 'local', 
     }, 
    }, 
    'root': { 
     'handlers': ['console1', 'console2'], 
    } 
} 

if __name__ == '__main__': 
    logging.config.dictConfig(LOGGING) 
    logging.warning('Look out!') 

當我運行上面,我得到:

2015-10-17 12:20:36,217 Look out! 
2015-10-17 13:20:36,217 Look out! 

定製實例的使用'()'關鍵的是在記錄here段落開頭All other keys ...

相關問題