第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

無法使用中間件將用戶名添加到日志記錄

無法使用中間件將用戶名添加到日志記錄

四季花海 2022-10-25 10:31:03
我正在嘗試記錄(默認(rèn)情況下)username和project(可以從request對(duì)象決定)。我不想context手動(dòng)添加到每個(gè)日志。問題是我無法Django添加request或直接添加username到. 我嘗試了幾十種方法。projectLogRecord這是我的代碼:中間件.pyimport threadinglocal = threading.local()class LoggingRequestMiddleware:    def __init__(self, get_response):        self.get_response = get_response        # One-time configuration and initialization.    def __call__(self, request):        # Code to be executed for each request before        # the view (and later middleware) are called.        setattr(local, 'request', request)        response = self.get_response(request)        # Code to be executed for each request/response after        # the view is called.        return response設(shè)置.pydef add_username_to_log(record):local = threading.local()record.username = '-'request = getattr(local,'request',None)print(request)return TrueLOGGING = {    'version': 1,    'disable_existing_loggers': False,    'formatters': {        'verbose': {            'format': LOGGING_VERBOSE_FORMAT,            'style': '{',        },    },    'filters': {        'context_filter': {            '()': 'django.utils.log.CallbackFilter',            'callback': add_username_to_log,        },    },    'handlers': {        'console': {            'level': DEFAULT_LOG_LEVEL,            'class': 'logging.StreamHandler',            'formatter': 'verbose',            'filters': ['context_filter'],        },        'file_main': {            'level': DEFAULT_LOG_LEVEL,            'class': 'logging.handlers.RotatingFileHandler',            'filename': os.path.join(LOG_PATH, 'main.log'),            'maxBytes': DEFAULT_LOG_SIZE,            'formatter': 'verbose',            'filters': ['context_filter'],            'backupCount': 0,        },    },    'loggers': {        '': {            'handlers': ['file_main'],            'level': DEFAULT_LOG_LEVEL,            'propagate': False,        },    },}但request對(duì)象始終是None。你知道為什么嗎?
查看完整描述

1 回答

?
郎朗坤

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊

threading.local()每次返回一個(gè)新對(duì)象,你必須讀取和寫入同一個(gè)對(duì)象。


locals_a = threading.local()

locals_a.foo = 1

hasattr(locals_a, 'foo')  # True

locals_b = threading.local()

hasattr(locals_b, 'foo')  # False

您需要在 1 個(gè)地方定義您的 locals 對(duì)象,然后您可以在每次需要訪問請(qǐng)求并讀取和寫入該對(duì)象的任何地方導(dǎo)入該對(duì)象。作為一個(gè)基本示例,這應(yīng)該有效


def add_username_to_log(record):

    from middleware import local

    request = getattr(local,'request',None)


查看完整回答
反對(duì) 回復(fù) 2022-10-25
  • 1 回答
  • 0 關(guān)注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)