bubbleeee

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

request id:一个请求的唯一标识【一个容易忽略的小细节,某次没打出来,出现问题日志无法进行统计】

  • 定义 Middleware 和 Logging Filter(路径 app-log_trace.py)
 1 class TraceInfoFilter(logging.Filter):
 2     """
 3     This is a filter which injects contextual information into the log.
 4     """
 5 
 6     def filter(self, record):
 7         record.request_id = getattr(local, 'request_id', "none")
 8         return True
 9 
10 
11 class RequestIDMiddleware(MiddlewareMixin):
12     def process_request(self, request):
13         trace_id = str(uuid.uuid4())
14         local.request_id = trace_id
15 
16     def process_response(self, request, response):
17         if hasattr(request, 'request_id'):
18             response['X-Request-ID'] = local.request_id
19         try:
20             del local.request_id
21         except AttributeError:
22             pass
23         return response

 

 

 

 

 

 

  • 在 settings.py 中注册 自定义的 Middleware 并使用 filter

MIDDLEWARE配置

 1 MIDDLEWARE = (
 2     'corsheaders.middleware.CorsMiddleware',
 3     'promotion.app.log_trace.RequestIDMiddleware',# 如果django目录有多层,需要注意这个路径
 4     'django.contrib.sessions.middleware.SessionMiddleware',
 5     'django.middleware.common.CommonMiddleware',
 6     'django.middleware.csrf.CsrfViewMiddleware',
 7     'django.contrib.auth.middleware.AuthenticationMiddleware',
 8     # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 默认实现了
 9     # 'django.contrib.messages.middleware.MessageMiddleware',/
10     # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
11     'django.middleware.security.SecurityMiddleware',
12 )

LOGGING配置filter

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    #'filters': {
    #   'require_debug_false': {
    #      '()': 'django.utils.log.RequireDebugFalse'
    # },
    #  'trace_info_filter': {
    #    '()': TraceInfoFilter
    #},
    'filters': {
        'request_id': {
            '()': TraceInfoFilter
        }

    },
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(pathname)s:%(lineno)d::[%(request_id)s]  %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
            'filters':['request_id']
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True,
        },
        'file': {
            'class': 'utils.safe_file_handler.CommonTimedRotatingFileHandler',
            'filename': os.path.join(LOG_PATH, "app.operation.log"),
            'when': 'midnight',
            'interval': 1,
            'backupCount': 5,
            'formatter': 'verbose',
            'filters': ['request_id', ],
        },
        'file2': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': os.path.join(LOG_PATH, "app.debug.log"),
            'when': 'midnight',
            'interval': 1,
            'backupCount': 5,
            'formatter': 'verbose',
            'filters': ['request_id', ],
        },
    },
    'loggers': {
        '': {
            'handlers': ['file'], # 前期开发测试时加上console方便点,后续删掉
            'propagate': True,
            'level': 'INFO',
        },
        'django': {
            'handlers': ['null'],
            'propagate': True,
            'level': 'DEBUG',
        },
        'django.request': {# 通过logging.getLogger('django.db.backends')加载,propagate是要不要往root里面也写
            'handlers': ['file2'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django.db.backends': {
            'handlers': ['file2'],
            'level': 'INFO',
            'propagate': False,
        },
    }
}

 

 

 

 

-------------------------------完-------------------------------

 

posted on 2021-09-09 12:19  bubbleeee  阅读(804)  评论(0编辑  收藏  举报