1、在项目中添加:Log.py
# 自定义中间件
import json
import threading
import logging
import socket
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
local = threading.local()
class RequestLogFilter(logging.Filter):
"""
日志过滤器,将当前请求线程的request信息保存到日志的record上下文
record带有formater需要的信息。
"""
def filter(self, record):
record.hostname = getattr(local, 'hostname', None) # 主机名称
record.dest_ip = getattr(local, 'dest_ip', None) # 服务器IP
record.username = getattr(local, 'username', None) # 用户
record.source_ip = getattr(local, 'source_ip', None) # 客户端IP
record.request_path = getattr(local, 'request_path', None)
record.request_params = getattr(local, 'request_params', None)
return True
class RequestLogMiddleware(MiddlewareMixin):
"""
将request的信息记录在当前的请求线程上。
"""
def process_request(self, request):
local.hostname = socket.gethostname()
local.dest_ip = socket.gethostbyname(local.hostname)
local.username = request.user
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '')
if x_forwarded_for:
source_ip = x_forwarded_for.split(',')[0] # 所以这里是真实的ip
else:
source_ip = request.META.get('REMOTE_ADDR') # 这里获得代理ip
local.source_ip = source_ip
local.request_path = request.path
local.request_params = json.dumps(request.POST)
def process_response(self, request, response):
return response
2、修改项目的settings.py
# 日志文件配置
LOGGING = {
'version': 1,
'disable_existing_loggers': True, # 是否禁用已经存在的日志器
'formatters': { # 日志信息显示的格式
'verbose': {'format': '[%(asctime)s %(levelname)s [%(module)s:%(lineno)d] [%(process)d:%(threadName)s] %(message)s'},
'simple': {'format': '%(asctime)s %(levelname)s [%(module)s:%(lineno)d] %(message)s'},
'complex': {'format': '[%(hostname)s source_ip:%(source_ip)s] [%(asctime)s %(levelname)s [%(module)s:%(lineno)d] [%(process)d:%(threadName)s] %(message)s'},
},
'filters': {
'new_add': {
'()': 'ironfort.Log.RequestLogFilter',
},
},
'handlers': { # 日志处理方法
'console': { # 向终端中输出日志
'level': 'INFO',
'filters': ['new_add'],
'class': 'logging.StreamHandler',
'formatter': 'complex'
},
},
'loggers': {
'django': { # 定义了一个名为django的日志器
'handlers': ['console'], # 可以同时向终端与文件中输出日志
'level': 'INFO', # 日志器接收的最低日志级别
'propagate': False, # 是否继承父类的log信息,0:否 1:是
},
}
}
文章评论