[英]Python/Django logging with extra options
我在Django中有一個日志配置文件,該文件使用sys.exc_info()
元組並在日志記錄時將它們作為額外選項傳遞(請參見下面格式化程序中的變量type
和value
)
'formatters': {
'basic': {
'format': '%(levelname)s %(lineno)d %(message)s %(type)s %(value)s'
},
},
這是我記錄錯誤的方式:
except Exception, e:
extra = {'type':sys.exc_info()[0], 'value':sys.exc_info()[1]}
logger.warning('My message', extra=extra)
但是,如果我只是寫
except Exception, e:
logger.warning('My message')
我得到一個例外,因為變量type
和value
現在在格式化程序中未定義。 我如何告訴格式化程序將這些變量視為可選變量,即如果我在記錄時傳遞它們,然后使用它們,否則跳過它們。
我建議您不要在日志記錄調用中顯式傳遞exc_info
元組部分。 相反,請注意,如果發生異常並且您傳遞了exc_info=True
或exc_info=sys.exc_info()
,則該元組已經存儲在LogRecord
的exc_info
屬性中。 您可以在格式化程序中訪問它們,因此您可以使用Formatter
子類或Filter
子類將元組的一部分轉換為其他LogRecord
屬性,這些屬性可以在格式字符串中引用(或者另外,由自定義Formatter
子類處理) )。
更新:您可以在格式字符串中以%(exc_info)s
進行引用,但這只會顯示元組。 請注意,可以重寫Formatter
的formatException
方法以顯示異常。 默認值將格式化標准回溯-我知道您不希望這種情況發生嗎?
class MyFormatter(logging.Formatter):
def formatException(self, exc_info):
return 'exception: %s %s' % exc_info[:2])
那將打印單行而不是完整的追溯,但是會換行。 或者您可以使用類似的方法:
class MyFormatter(logging.Formatter):
def format(self, record):
if isinstance(record.exc_info, tuple):
record.exc_data = ' %s %s' % record.exc_info[:2]
else:
record.exc_data = ''
return super(MyFormatter, self).format(record)
def formatException(self, exc_info):
return ''
然后使用其中包含%(exc_data)s
的格式字符串。
使用這兩種方法,您需要確保將真正的exc_info
傳遞到日志記錄調用中,以確保將異常數據保存在LogRecord
。 記錄器的exception()
方法執行此操作(級別為ERROR
)。
進一步更新:要使用Filter
子類執行此操作,可以執行以下操作:
class MyFilter(logging.Filter):
def filter(self, record):
if isinstance(record.exc_info, tuple):
record.exc_data = ' %s %s' % record.exc_info[:2]
else:
record.exc_data = ''
# The next bit is to prevent the standard Formatter from writing
# a traceback
record.exc_info = None
return True # otherwise, the record doesn't get output
這應該與前面的示例具有相同的效果,因此您可以使用相同的格式字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.