logging配置:
# LOGGING 模块
root_path
=
os.path.dirname(os.path.dirname(os.path.abspath(
'__file__'
)))
root_par_path
=
os.path.dirname(root_path)
log_path
=
os.path.join(root_par_path,
'logs'
)
if
not
os.path.exists(log_path):
os.mkdir(log_path)
# 如果不存在这个logs文件夹,就自动创建一个
LOGGING
=
{
'version'
:
1
,
'disable_existing_loggers'
:
False
,
# 禁用已经存在的logger实例
'formatters'
: {
'standard'
: {
'format'
:
'%(levelname)s-%(asctime)s-%(filename)s:%(lineno)d-%(funcName)s > %(message)s'
},
},
# 过滤
'filter'
: {
},
# 具体处理日志方式
'handlers'
: {
# 默认记录所有日志
'default'
: {
'level'
:
'INFO'
,
'class'
:
'logging.handlers.RotatingFileHandler'
,
'filename'
: os.path.join(log_path,
'all-{}.log'
.
format
(time.strftime(
'%Y-%m-%d'
))),
'maxBytes'
:
1024
*
1024
*
5
,
# 文件大小
'backupCount'
:
5
,
# 备份数
'formatter'
:
'standard'
,
# 输出格式
'encoding'
:
'utf-8'
,
# 设置默认编码,否则打印出来汉字乱码
},
# 输出错误日志
'error'
: {
'level'
:
'ERROR'
,
'class'
:
'logging.handlers.RotatingFileHandler'
,
'filename'
: os.path.join(log_path,
'error-{}.log'
.
format
(time.strftime(
'%Y-%m-%d'
))),
'maxBytes'
:
1024
*
1024
*
5
,
# 文件大小
'backupCount'
:
5
,
# 备份数
'formatter'
:
'standard'
,
# 输出格式
'encoding'
:
'utf-8'
,
# 设置默认编码
},
# 控制台输出
'console'
: {
'level'
:
'DEBUG'
,
'class'
:
'logging.StreamHandler'
,
'formatter'
:
'standard'
},
# 输出info日志
'info'
: {
'level'
:
'INFO'
,
'class'
:
'logging.handlers.RotatingFileHandler'
,
'filename'
: os.path.join(log_path,
'info-{}.log'
.
format
(time.strftime(
'%Y-%m-%d'
))),
'maxBytes'
:
1024
*
1024
*
5
,
'backupCount'
:
5
,
'formatter'
:
'standard'
,
'encoding'
:
'utf-8'
,
# 设置默认编码
},
},
# 配置用哪几种 handlers 来处理日志
'loggers'
: {
# 类型 为 django 处理所有类型的日志, 默认调用
'django'
: {
'handlers'
: [
'default'
,
'console'
],
'level'
:
'INFO'
,
'propagate'
:
False
},
# log 调用时需要当作参数传入
'error'
: {
'handlers'
: [
'error'
,
'console'
],
'level'
:
'ERROR'
,
'propagate'
:
True
},
}
}
使用和日志输出:
import
logging
try
:
if
res[
'code'
]
=
=
10000
and
res[
'message'
]
=
=
'OK'
:
return
HttpResponse(user
+
res[
'message'
])
else
:
return
HttpResponse(
"记录失败"
+
res[
'message'
])
except
Exception as e:
logger
=
logging.getLogger(
'error'
)
logger.error(
str
(e))
return
HttpResponse(
"哦哦,出错了"
)