簡體   English   中英

python logging.Logger:覆蓋makeRecord

[英]python logging.Logger: overriding makeRecord

我有一個格式化程序,它期望記錄“ user_id”中有特殊屬性,但並不總是存在(有時我使用特殊logging.Filter將其添加到記錄中)。 我試圖覆蓋這樣的logging.Logger的makeRecord方法:

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)-15s user_id=%(user_id)s %(filename)s:%(lineno)-15s: %(message)s')


class OneTestLogger(logging.Logger):
    def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
        rv = logging.Logger.makeRecord(self, name, level, fn, lno,
                                       msg, args, exc_info,
                                       func, extra)
        rv.__dict__.setdefault('user_id', 'master')
        return rv


if __name__ == '__main__':

    logger = OneTestLogger('main')
    print logger
    logger.info('Starting test')

但這似乎不起作用,我不斷得到:

< .MyLogger實例位於0x7f31a6a5b638>

找不到記錄程序“主”的處理程序

我究竟做錯了什么? 謝謝。

遵循《 日志記錄食譜》中提供的指南。 只是第一部分,我沒有實現Filter(它也沒有出現在下面的引用中)。

這通常意味着,如果您需要對LogRecord做任何特殊的事情,則必須執行以下操作之一。

  1. 創建您自己的Logger子類,該子類將覆蓋Logger.makeRecord(),並在實例化您關心的所有記錄器之前使用setLoggerClass()對其進行設置。

我簡化了您的示例,僅添加了“主機名”:

import logging
from socket import gethostname

logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s - %(hostname)s - %(message)s')

class NewLogger(logging.Logger):
    def makeRecord(self, *args, **kwargs):
        rv = super(NewLogger, self).makeRecord(*args, **kwargs)
        # updating the rv value of the original makeRecord
        # my idea is to use the same logic than a decorator by
        # intercepting the value return by the original makeRecord
        # and expanded with what I need
        rv.__dict__['hostname'] = gethostname()
        # by curiosity I am checking what is in this dictionary
        # print(rv.__dict__)
        return rv

logging.setLoggerClass(NewLogger)

logger = logging.getLogger(__name__)
logger.info('Hello World!')

請注意,此代碼適用於python 2.7

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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