推荐使用中间键.(方法二)
django-输出日志-方法一(不用这个了)
settings.py 中的配置
import logging
import os
import time
# 创建日志文件夹路径
LOG_PATH = os.path.join(BASE_DIR, 'log')
# 如过地址不存在,则自动创建log文件夹
if not os.path.isdir(LOG_PATH):
os.mkdir(LOG_PATH)
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'simple': {
'format': '[%(asctime)s] %(levelname)s : %(message)s'
},
'verbose': {
'format': '[%(asctime)s] %(levelname)s %(module)s %(process)d %(thread)d : %(message)s'
},
'standard': {
'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(levelname)s]- %(message)s'
},
},
# handlers:用来定义具体处理日志的方式,可以定义多种,"default"就是默认方式,"console"就是打印到控制台方式。file是写入到文件的方式,注意使用的class不同
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True,
},
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_PATH, f"{time.strftime('%Y-%m-%d')}.log"),
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'simple',
},
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
},
# log记录器,配置之后就会对应的输出日志
'loggers': {
'django': {
'handlers': ['console', 'default'],
'level': 'INFO',
'propagate': True,
},
},
}
logger = logging.getLogger("django")
这是我从网上复制的,但是具体的写法我也不清楚
使用在views.py中
from django_project_name.settings import logger # 当前项目的名称
# 最基本的用法 简单用法.
def run_test(request):
logger.info('get_method')# get_method 可以自定义的.
try:
1 is 1
except Exception as e:
logger.error(str(e))
显示结果
[2021-12-23 09:59:19,626] INFO : Watching for file changes with StatReloader
[2021-12-23 09:59:38,720] INFO : get����
[2021-12-23 09:59:38,741] WARNING : Forbidden: /app_1/login/
[2021-12-23 09:59:38,742] WARNING : "GET /app_1/login/ HTTP/1.1" 403 5185
[2021-12-23 09:59:39,663] INFO : "GET /static/rest_framework/css/bootstrap-tweaks.css HTTP/1.1" 200 3385
[2021-12-23 09:59:39,663] INFO : "GET /static/rest_framework/css/default.css HTTP/1.1" 200 1152
[2021-12-23 09:59:39,666] INFO : "GET /static/rest_framework/js/ajax-form.js HTTP/1.1" 200 3597
[2021-12-23 09:59:39,667] INFO : "GET /static/rest_framework/css/prettify.css HTTP/1.1" 200 817
[2021-12-23 09:59:39,667] INFO : "GET /static/rest_framework/js/csrf.js HTTP/1.1" 200 1719
[2021-12-23 09:59:39,671] INFO : "GET /static/rest_framework/js/bootstrap.min.js HTTP/1.1" 200 39680
[2021-12-23 09:59:39,672] INFO : "GET /static/rest_framework/js/prettify-min.js HTTP/1.1" 200 13632
[2021-12-23 09:59:39,672] INFO : "GET /static/rest_framework/js/jquery-3.5.1.min.js HTTP/1.1" 200 89476
[2021-12-23 09:59:39,673] INFO : "GET /static/rest_framework/js/default.js HTTP/1.1" 200 1268
[2021-12-23 09:59:39,675] INFO : "GET /static/rest_framework/css/bootstrap.min.css HTTP/1.1" 200 121457
[2021-12-23 09:59:39,728] INFO : "GET /static/rest_framework/img/grid.png HTTP/1.1" 200 1458
[2021-12-23 09:59:39,826] INFO : "GET /favicon.ico HTTP/1.1" 200 26
django-输出日志-方法二 (中间键)
在django项目下创建
log_middleware
文件夹,在创建log_middleware.py
文件.
# -*- coding: utf-8 -*-
"""
@Time : 2022/4/7 14:08
@Project : django_role_tree
"""
import logging
import time
from django.utils.deprecation import MiddlewareMixin
logger = logging.getLogger(__name__)
class LogMiddle(MiddlewareMixin):
# 日志处理中间件
def process_request(self, request):
# 存放请求过来时的时间
request.init_time = time.time()
return None
def process_response(self, request, response):
try:
# 耗时
localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 请求路径
path = request.get_full_path_info()
# 请求方式
method_1 = request.method
# 响应状态码
status_code = response.status_code
# 获取ip地址
if 'HTTP_X_FORWARDED_FOR' in request.META:
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
# 根据响应类型获取值
if method_1 == "POST":
data = request.POST
elif method_1 == "GET":
data = request.GET
message = f"request_path:{path},request_method:{method_1},use_time:{localtime},status_code:{status_code},address_ip:{ip},request_cont:{data}"
logger.info(message)
except Exception as e:
logger.critical(f'系统错误,{request.get_full_path_info()},{request.body}')
return response
去
settings.py
下调整东西.记得添加中间键
中间键
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',
'log_middleware.log_middleware.LogMiddle',# 记得添加中间键
]
log配置
写到settings.py底下就行了
# 创建日志文件夹路径
LOG_PATH = os.path.join(BASE_DIR, 'log')
# 如过地址不存在,则自动创建log文件夹
if not os.path.isdir(LOG_PATH):
os.mkdir(LOG_PATH)
LOGGING = {
'version': 1,
# 禁用日志
'disable_existing_loggers': False,
'loggers': {
'': {
'handlers': ['console'],
'level': 'INFO',
}
},
'handlers': {
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_PATH, f"{time.strftime('%Y-%m-%d')}.log"),
'maxBytes': 1024 * 1024 * 5, # 文件大小
'backupCount': 5, # 备份数
'encoding': 'utf-8', # 设置默认编码,否则打印出来汉字乱码
},
'console': {
'filename':os.path.join(LOG_PATH, f"{time.strftime('%Y-%m-%d')}.log"),
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
# 日志文件大小:5M
'maxBytes': 5 * 1024 * 1024,
'encoding': "utf-8"
}
},
'formatters': {
'default': {
'format': '%(asctime)s %(message)s'
}
}
}
方法二延申,中间键优化
settings.py
L# ============================日志
SUCCESS_LOG_PATH = os.path.join(BASE_DIR, 'log/success')
ABNORMAL_LOG_PATH = os.path.join(BASE_DIR, 'log/abnormal')
for item in [SUCCESS_LOG_PATH, ABNORMAL_LOG_PATH]:
if not os.path.exists(item):
os.makedirs(item)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'loggers': {
# 在这里添加 分类 就是自己想要这个日志 存储什么类型的.
'success': {
'handlers': ['success'], # handlers 是 具体的对 日志类型 的调整.
'level': 'INFO',
},
'abnormal': {
'handlers': ['abnormal'],
'level': 'WARNING',
}
},
'handlers': {
'abnormal': {
'level': 'WARNING',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(ABNORMAL_LOG_PATH, f"abnormal-{time.strftime('%Y-%m-%d-%H')}.log"),
'maxBytes': 1024 * 1024 * 5, # 文件大小
'backupCount': 5, # 备份数
'encoding': 'utf-8', # 设置默认编码,否则打印出来汉字乱码
},
'success': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(SUCCESS_LOG_PATH, f"success-{time.strftime('%Y-%m-%d-%H')}.log"),
'maxBytes': 5 * 1024 * 1024,
'encoding': "utf-8"
}
},
'formatters': {
'default': {
'format': '%(asctime)s %(message)s'
}
}
}
在自己的自定义中间键中进行添加就行了.
全局请求捕获
import logging
import time
from django.utils.deprecation import MiddlewareMixin
logger = logging.getLogger('success') # 在这里添加 分类 就是自己想要这个日志 存储什么类型的.
class Success_Middleware(MiddlewareMixin):
"""
日志处理中间件
"""
def process_request(self, request):
return None
def process_response(self, request, response):
try:
# 耗时
localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 请求路径
path = request.get_full_path_info()
# 请求方式
method_1 = request.method
# 响应状态码
status_code = response.status_code
# 获取ip地址
if 'HTTP_X_FORWARDED_FOR' in request.META:
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
# 根据响应类型获取值
data = request.body.decode()
message = {f"request_path:{path},request_method:{method_1},use_time:{localtime},status_code:{status_code},address_ip:{ip},request_content:{data}"}
logger.info(message)
except Exception as e:
logger.critical(f'ERROR,{request.get_full_path_info()},{request.body},{str(ValueError(e))}')
return response
try_middleware 异常捕获
import logging
import time
import traceback
from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
logger = logging.getLogger('abnormal')
Fa_Code = {
"code": 400,
"msg": "",
"err": ""
}
class Abnormal_Middleware(MiddlewareMixin):
"""
拦截异常请求的日志中间件
"""
def process_exception(self, request, exception):
try:
# 耗时
localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 请求路径
path = request.get_full_path_info()
# 请求方式
method_1 = request.method
# 获取ip地址
if 'HTTP_X_FORWARDED_FOR' in request.META:
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
# 根据响应类型获取值
data = request.body.decode()
message = {f"request_path:{path},request_method:{method_1},use_time:{localtime},address_ip:{ip},request_content:{data},error_info:{str(exception)}"}
logger.critical(message)
logger.critical(traceback.format_exc()) # 记录具体报错位置.
except Exception as e:
logger.critical(f'SYS_ERROR,{request.get_full_path_info()},{request.body},{str(ValueError(e))}')
Fa_Code['msg'] = "当前您的请求发生异常"
Fa_Code['err'] = str(exception)
return JsonResponse(Fa_Code, status=Fa_Code['code'])
-
all_req: request_path:/api_1/run_1/,request_method:GET,use_time:2022-05-07 11:32:33,status_code:400,address_ip:127.0.0.1,request_content:
-
views_error: request_path:/api_1/run_1/,request_method:GET,use_time:2022-05-07 11:32:33,address_ip:127.0.0.1,request_content:,error_info:unsupported operand type(s) for +: 'int' and 'str'
视图函数 demo
# 我是故意写成这样导致报错,才能查看自己的写的log是都生效了.
@require_http_methods(['GET'])
def run_1(request):
value = signer.signature('My string')
1+"2"
return JsonResponse({"code": 200, "data": value}, safe=False)