【问题标题】:Can't add username to logging record using Middleware无法使用中间件将用户名添加到日志记录
【发布时间】:2020-08-09 20:04:46
【问题描述】:

我正在尝试记录(默认情况下)usernameproject(可以从 request 对象决定)。我不想手动将context 添加到每个日志中。

问题是我不能让Djangorequest 或直接usernameproject 添加到LogRecord。我尝试了几十种方法。

这是我的代码:

中间件.py

import threading
local = 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

settings.py

def add_username_to_log(record):
local = threading.local()
record.username = '-'
request = getattr(local,'request',None)
print(request)

return True

LOGGING = {
    '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 对象始终是None。你知道为什么吗?

【问题讨论】:

  • 不需要读取本地对象的请求吗?
  • @IainShelvington 是的,你是对的,大错特错。但是,它总是无(我已经编辑了问题)

标签: python django logging django-logging


【解决方案1】:

threading.local()每次都返回一个新对象,你必须读写同一个对象。

locals_a = threading.local()
locals_a.foo = 1
hasattr(locals_a, 'foo')  # True
locals_b = threading.local()
hasattr(locals_b, 'foo')  # False

您需要在 1 个地方定义您的本地对象,然后您可以在每次需要访问请求并读取和写入该对象的任何地方导入该对象。作为一个基本示例,这应该可以工作

def add_username_to_log(record):
    from middleware import local
    request = getattr(local,'request',None)

【讨论】:

  • 我没有任何线索。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
  • 2021-02-12
  • 1970-01-01
  • 2015-02-16
相关资源
最近更新 更多