2010-06-17 75 views
4

我想通過 自定義日誌處理程序或自定義日誌記錄程序類 來創建自定義日誌記錄程序方法,並將日誌記錄分派到不同的目標。如何在Python中的自定義logging.Handler中獲取日誌記錄的級別?

例如:

log = logging.getLogger('application') 

log.progress('time remaining %d sec' % i) 
    custom method for logging to: 
      - database status filed 
      - console custom handler showing changes in a single console line 

log.data(kindOfObject) 
    custom method for logging to: 
      - database 
      - special data format 

log.info 
log.debug 
log.error 
log.critical 
    all standard logging methods: 
     - database status/error/debug filed 
     - console: append text line 
     - logfile 

如果我通過重寫EMIT方法, 我不能distinguishe日誌記錄的水平使用自定義LoggerHandler。 是否有任何其他可能性獲取記錄級別的運行時信息?

class ApplicationLoggerHandler(logging.Handler): 

    def emit(self, record): 
    # at this place I need to know the level of the record (info, error, debug, critical)? 

有什麼建議嗎?

回答

9

recordLogRecord一個實例:

>>> import logging 
>>> rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao',(), False) 

,你的方法可以只訪問感興趣的屬性(我分裂dir的便於閱讀的結果):

>>> dir(rec) 
['__doc__', '__init__', '__module__', '__str__', 'args', 'created', 
'exc_info', 'exc_text', 'filename', 'funcName', 'getMessage', 'levelname', 
'levelno', 'lineno', 'module', 'msecs', 'msg', 'name', 'pathname', 'process', 
'processName', 'relativeCreated', 'thread', 'threadName'] 
>>> rec.levelno 
1 
>>> rec.levelname 
'Level 1' 

等等。 (rec.getMessage()是您在rec上使用的一種方法 - 將消息格式化爲字符串,插入參數)。

+0

非常感謝! – koleto 2010-06-17 15:40:13

+0

@ koleto,不客氣! – 2010-06-17 17:28:59

相關問題