django 日誌默認打印 request 請求信息

django 日誌默認打印 request 請求信息

需求

請求view中手動打印日誌時中插入request的以下信息(每一個request請求都記錄能夠使用中間件進行解決,但這裏僅僅是在須要的地方手動打印):python

#統一附加日誌內容

ADD_LOG = r'''{"username": request.user, "path": request.path, "request_id": request.id, "login_id": request.login_id}'''
複製代碼

舊的解決辦法

在每次須要打印日誌時,經過 logging extra 進行額外的打印信息添加:
每次手動添加一樣的extra很是的不優雅。django

image.png

新的解決方案

django 自帶log系統官方文檔session

一、熟悉python的logging模塊結構。

  1. Loggers
  2. Handlers
  3. Filters
  4. Formatters

二、django中間件存儲request信息。

class RequestLogMiddleware(MiddlewareMixin):
    """ 將request的信息記錄在當前的請求線程上 """
    def process_request(self, request):
        # 統一附加日誌內容
        # ADD_LOG = r'''{"username": request.user, "path": request.path, "request_id": request.id, "login_id": request.login_id}'''
        local.path = request.path
        local.request_id = request.id
        local.login_id = request.login_id
        local.username = request.user.username
複製代碼

三、logging的filters模塊添加request信息。

import logging

class RequestLogFilter(logging.Filter):
    """ 日誌過濾器,將當前請求線程的request信息保存到日誌的record上下文 """
    def filter(self, record):
        record.request_id = getattr(local, 'request_id', "none")
        record.path = getattr(local, 'path', "none")
        record.login_id = getattr(local, 'login_id', "none")
        record.username = getattr(local, 'username', "none")
        record.appName = getattr(local, "appName", "none")
        return True
複製代碼

四、實現原理及代碼

經過 local = threading.local()app

middleware-waiwen文件代碼:spa

import threading
import logging
try:
    from django.utils.deprecation import MiddlewareMixin  # Django 1.10.x
except ImportError:
    MiddlewareMixin = object  # Django 1.4.x - Django 1.9.x

local = threading.local()
class RequestLogFilter(logging.Filter):
    """ 日誌過濾器,將當前請求線程的request信息保存到日誌的record上下文 record帶有formater須要的信息。 """
    def filter(self, record):
        record.request_id = getattr(local, 'request_id', "none")
        record.path = getattr(local, 'path', "none")
        record.login_id = getattr(local, 'login_id', "none")
        record.username = getattr(local, 'username', "none")
        return True

class RequestLogMiddleware(MiddlewareMixin):
    """ 將request的信息記錄在當前的請求線程上。 """
    def process_request(self, request):
        # 統一附加日誌內容
        # ADD_LOG = r'''{"username": request.user, "path": request.path, "request_id": request.id, "login_id": request.login_id}'''
        local.path = request.path
        local.request_id = request.id
        local.login_id = request.login_id
        local.username = request.user.username
複製代碼

settings 文件配置.net

MIDDLEWARE = [
    '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',
  
    'wcloud.middleware-waiwen.RequestLogMiddleware'  
     #使用該中間件
     #將當前的request信息保存到當前線程供日誌打印使用
]


LOGGING = {
        # 日誌相關
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {
                'format': '{"date": "%(created)f", "level": "%(levelname)s", "funcName": "%(module)s.%(funcName)s:%(lineno)d", "msg": "%(message)s"}'},  # 日誌格式
            'custom': {
              #該格式化中包含有過濾器record新增的字段
                'format': '{"date": "%(created)f", "level": "%(levelname)s", "funcName": "%(module)s.%(funcName)s:%(lineno)d", "request_id": "%(request_id)s","login_id": "%(login_id)s", "username": "%(username)s", "path": "%(path)s","msg": "%(message)s"}'
            },
        },
        'filters': {
            #註冊該過濾器
            'request_info': {'()': 'wcloud.middleware-waiwen.RequestLogFilter'}
        },
        'handlers': {
            'log': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'custom',
              #在該過handler中使用該過濾器
                'filters': ['request_info'], 
            },
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'standard',
            },
        },
        'loggers': {
            'django': {
                'handlers': ['console'],
                'level': 'ERROR',
                'propagate': False
            },
            'django.request': {
                'handlers': ['console'],
                'level': 'ERROR',
                'propagate': False
            },
            'django.db.backens': {
                'handlers': ['console'],
                'level': 'DEBUG',
                'propagate': False
            },
            'log': {
                'handlers': ['log'],
                'level': 'INFO',
                'propagate': True
            },
           
        }
    }
複製代碼

五、效果

image.png

參考:

給Django日誌加上request_id線程

相關文章
相關標籤/搜索