无法使用中间件将用户名添加到日志记录

时间:2020-04-26 10:13:03

标签: python django logging django-logging

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

问题是我无法让Django添加request或直接将usernameproject添加到LogRecord中。我尝试了数十种方法。

这是我的代码:

middlewares.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。你知道为什么吗?

1 个答案:

答案 0 :(得分: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个地方定义locals对象,然后可以将其导入到需要访问请求并每次都对该对象进行读写的所有位置。作为一个基本示例,这应该有效

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