Django日志带有自定义过滤器的用户名

时间:2018-12-03 14:52:10

标签: django

我试图创建自定义日志记录过滤器,以记录每个请求的用户名,如以下链接所示:

django logging - django.request logger and extra context

但是我的请求没有用户属性。

这是我的代码:

class RequestUsernameFilter:
    def filter(self, record):
        request = record.request
        record.username = request.user.username
        return True

请求属性: enter image description here

AttributeError:“套接字”对象没有属性“用户”

我的配置:

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
    'username': {
        '()': 'myapp.RequestUsernameFilter',
    },
},
'handlers': {
    'requests': {
        'level': 'DEBUG',
        'class': 'logging.handlers.RotatingFileHandler',
        'filename': './requests.log',
        'maxBytes': 102400,
        'backupCount': 5,
        'formatter': 'verbose',
        'filters': ['username'],
    }
},
'formatters': {
    'verbose': {
        'format': '%(levelname)s %(asctime)s %(username)s %(thread)d %(module)s %(funcName)s  %(message)s'
    }
},
'loggers': {
    'django.server': {
        'handlers': ['requests'],
        'level': 'DEBUG',
        'propagate': True,
    },
},

}

MIDDLEWARE:

    MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.BrokenLinkEmailsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware']

0 个答案:

没有答案