Django日志处理
settings配置
###########
# LOGGING #
###########
BASE_LOG_DIR = os.path.join(os.path.dirname(BASE_DIR), "log")
if not os.path.exists(BASE_LOG_DIR):
os.mkdir(BASE_LOG_DIR)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
# 格式
'formatters': {
'standard': {
"format": "%(asctime)s - (%(name)s)[%(levelname)s][%(host)s]: "
+ "%(request)s %(message)s %(status)d %(byte)d",
"datefmt": "[%Y-%m-%d %H:%M:%S %z]",
"class": "utils.logs.JSONFormatter", # 需要自己配置
},
'simple': {
'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
},
'collect': {
'format': '%(message)s'
}
},
# 过滤器
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
# 处理器
'handlers': {
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "luffy_info.log"), # 日志文件
'maxBytes': 1024 * 1024 * 50, # 日志大小 50M
'backupCount': 3,
'formatter': 'standard',
'encoding': 'utf-8',
},
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "err.log"), # 日志文件
'maxBytes': 1024 * 1024 * 50, # 日志大小 50M
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8',
},
'collect': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "info.log"),
'maxBytes': 1024 * 1024 * 50, # 日志大小 50M
'backupCount': 5,
'formatter': 'collect',
'encoding': "utf-8"
}
},
'loggers': {
'': {
'handlers': ['default', 'console', 'error'],
'level': 'DEBUG',
'propagate': True,
},
'collect': {
'handlers': ['console', 'collect'],
'level': 'INFO',
}
},
}
视图使用
def log(request):
"""
`django` 日志系统
文档参见: https://docs.djangoproject.com/en/1.11/topics/logging/
"""
import logging
logger = logging.getLogger('django.request')
logger.error("错误信息")
return HttpResponse("OK")
重写log输出模式
import json
import logging
import datetime
REMOVE_ATTR = [
"filename", "module", "exc_text", "stack_info", "created", "relativeCreated", "exc_info", "msg",
"request",
]
class JSONFormatter(logging.Formatter):
def format(self, record):
extra = self.build_record(record)
self.set_format_time(extra) # set time
# self.set_host_ip(extra) # set host name and host ip
extra['message'] = record.msg # set message
if record.exc_info:
extra['exc_info'] = self.formatException(record.exc_info)
if self._fmt == 'pretty':
return json.dumps(extra, indent=1, ensure_ascii=False)
else:
return json.dumps(extra, ensure_ascii=False)
@classmethod
def build_record(cls, record):
record = {
attr_name: record.__dict__[attr_name]
for attr_name in record.__dict__
if attr_name not in REMOVE_ATTR
}
return record
@classmethod
def set_format_time(cls, extra):
now = datetime.datetime.now()
format_time = now.strftime("%Y-%m-%d %H:%M:%S")
extra['timestamp'] = format_time
return format_time