1.settings.py MIDDLEWARE 新增中间件 'middleware_log.RequestLogMiddleware'
MIDDLEWARE = [ ... 'middleware_log.RequestLogMiddleware' ]
2.settings.py配置 LOGGING
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' '[%(levelname)s][%(message)s]' }, 'ops_standard': { 'format': '%(asctime)s %(ip)s user:%(username)s %(filename)s:%(lineno)d %(levelname)s http_reffer:%(' 'http_reffer)s path:%(path)s %(message)s ' }, }, 'filters': { 'new_add': {'()': 'middleware_log.RequestLogFilter'}, }, 'handlers': { # 'default': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(BASE_LOG_DIR, 'access.log'), 'backupCount': 5, # 备份数 'formatter': 'ops_standard', # 输出格式 'encoding': 'utf-8', # 设置默认编码,否则打印出来汉字乱码 'filters': ['new_add'], 'when': 'D', 'interval': 1, }, 'error': { 'level': 'ERROR', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(BASE_LOG_DIR, 'error.log'), 'backupCount': 5, # 备份数 'formatter': 'ops_standard', # 输出格式 'encoding': 'utf-8', # 设置默认编码 'filters': ['new_add'], 'when': 'D', 'interval': 1, }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'standard', }, 'info': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(BASE_LOG_DIR, 'info.log'), 'backupCount': 5, 'formatter': 'ops_standard', 'encoding': 'utf-8', # 设置默认编码 'filters': ['new_add'], 'when': 'D', 'interval': 1, }, }, 'loggers': { 'django': { 'handlers': ['console', 'default'], 'level': 'INFO', 'propagate': False }, # '' 调用时需要当作参数传入 '': { 'handlers': ['error', 'info', 'default'], 'level': 'INFO', 'propagate': True }, } }
3.项目里新增文件
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.ip = getattr(local, 'ip', None) record.username = getattr(local, 'username', None) record.http_reffer = getattr(local, 'http_reffer', None) record.path = getattr(local, 'path', None) return True class RequestLogMiddleware(MiddlewareMixin): """ 将request的信息记录在当前的请求线程上。 """ def process_request(self, request): temp_meta = request.META local.ip = request.META.get('HTTP_X_FORWARDED_FOR', None) local.username = xxx local.http_reffer = temp_meta.get('HTTP_REFERER', None) local.path = temp_meta.get('PATH_INFO', None) def process_response(self, request, response): return response
4.使用
import logging LOG = logging.getLogger() LOG.info('hahahhahaha') LOG.error('lalalalala')