簡體   English   中英

帶有額外選項的Python / Django日志記錄

[英]Python/Django logging with extra options

我在Django中有一個日志配置文件,該文件使用sys.exc_info()元組並在日志記錄時將它們作為額外選項傳遞(請參見下面格式化程序中的變量typevalue

'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')                                   

我得到一個例外,因為變量typevalue現在在格式化程序中未定義。 我如何告訴格式化程序將這些變量視為可選變量,即如果我在記錄時傳遞它們,然后使用它們,否則跳過它們。

我建議您不要在日志記錄調用中顯式傳遞exc_info元組部分。 相反,請注意,如果發生異常並且您傳遞了exc_info=Trueexc_info=sys.exc_info() ,則該元組已經存儲在LogRecordexc_info屬性中。 您可以在格式化程序中訪問它們,因此您可以使用Formatter子類或Filter子類將元組的一部分轉換為其他LogRecord屬性,這些屬性可以在格式字符串中引用(或者另外,由自定義Formatter子類處理) )。

更新:可以在格式字符串中以%(exc_info)s進行引用,但這只會顯示元組。 請注意,可以重寫FormatterformatException方法以顯示異常。 默認值將格式化標准回溯-我知道您希望這種情況發生嗎?

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM