Skip to content

Commit

Permalink
feat: add request log id
Browse files Browse the repository at this point in the history
  • Loading branch information
lihuacai168 committed Jun 15, 2023
1 parent b6da5e9 commit 5ba7c7f
Show file tree
Hide file tree
Showing 7 changed files with 95 additions and 23 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,5 @@ dmypy.json

# Pyre type checker
.pyre/

logs/
18 changes: 0 additions & 18 deletions .vscode/launch.json

This file was deleted.

84 changes: 83 additions & 1 deletion apidemo/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
Expand Down Expand Up @@ -41,6 +41,7 @@
]

MIDDLEWARE = [
'log_request_id.middleware.RequestIDMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
Expand Down Expand Up @@ -119,3 +120,84 @@
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

# log_id setting
LOG_REQUEST_ID_HEADER = "HTTP_X_REQUEST_ID"
GENERATE_REQUEST_ID_IF_NOT_IN_HEADER = True
REQUEST_ID_RESPONSE_HEADER = "RESPONSE_HEADER_NAME"

LOGGING = {
"version": 1,
"disable_existing_loggers": True,
"formatters": {
"standard": {
"format": "%(levelname)-2s [%(asctime)s] [%(request_id)s] %(name)s: %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
},
"color": {
"()": "colorlog.ColoredFormatter",
"format": "%(green)s%(asctime)s [%(request_id)s] %(name)s %(log_color)s%(levelname)s [pid:%(process)d] "
"[%(filename)s->%(funcName)s:%(lineno)s] %(cyan)s%(message)s",
"log_colors": {
"DEBUG": "black",
"INFO": "white",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "bold_red",
},
}
# 日志格式
},
"filters": {
"request_id": {"()": "log_request_id.filters.RequestIDFilter"},
"require_debug_true": {
"()": "django.utils.log.RequireDebugTrue", # 过滤器,只有当setting的DEBUG = True时生效
},
},
"handlers": {
"mail_admins": {
"level": "ERROR",
"class": "django.utils.log.AdminEmailHandler",
"include_html": True,
},
"default": {
"level": "DEBUG",
"class": "logging.handlers.RotatingFileHandler",
# 'filename': os.path.join(BASE_DIR, 'logs/../../logs/debug.log'),
"filename": os.path.join(BASE_DIR, "logs/info.log"),
"maxBytes": 1024 * 1024 * 50,
"backupCount": 5,
"formatter": "color",
"filters": ["request_id"],
},
"error": {
"level": "ERROR",
"class": "logging.handlers.RotatingFileHandler",
# 'filename': os.path.join(BASE_DIR, 'logs/../../logs/debug.log'),
"filename": os.path.join(BASE_DIR, "logs/error.log"),
"maxBytes": 1024 * 1024 * 50,
"backupCount": 5,
"formatter": "color",
"filters": ["request_id"],
},
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "color",
"filters": ["request_id"],
},
},
"loggers": {
"django": {
"handlers": ["default", "console", "error"],
"level": "INFO",
"propagate": True,
},
"employee": {
"handlers": ["default", "console", "error"],
"level": "INFO",
"propagate": True,
},

},
}
Binary file modified db.sqlite3
Binary file not shown.
11 changes: 7 additions & 4 deletions employee/views.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import logging
from typing import List, Optional
from ninja import Router, Query, Schema

from django.shortcuts import get_object_or_404
from ninja import Query, Router, Schema
from pydantic.fields import Field
from pydantic.types import conint



from common.schema import Message
from employee.models import Employee
from employee.schemas import EmployeeIn, EmployeeOut

router = Router(tags=['employees'])
router = Router(tags=["employees"])

logger = logging.getLogger(__name__)


class Filters(Schema):
Expand All @@ -21,6 +23,7 @@ class Filters(Schema):

@router.post("/employees")
def create_employee(request, payload: EmployeeIn):
logger.info(f"create employee, input: {payload.dict()}")
employee = Employee.objects.create(**payload.dict())
return {"id": employee.id}

Expand Down
Empty file added logs/.gitkeep
Empty file.
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ pydantic
pytz
sqlparse
typing-extensions

django-log-request-id
colorlog==4.0.2

0 comments on commit 5ba7c7f

Please sign in to comment.