[英]How to get the actual object passed to a logging call from a logging.Handler
[英]How to get the level of the logging record in a custom logging.Handler in Python?
我想通過自定義日志記錄處理程序或自定義記錄器類來創建自定義記錄器方法,並將記錄記錄分派給不同的目標。
例如:
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方法使用自定義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)?
有什么建議么?
record
是LogRecord的一個實例:
>>> 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
使用的一種方法 - 它將消息格式化為字符串,插入參數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.