import json
# 错误信息格式化
# 我的项目中user_id是用户的编号,可以根据自己需求,增加减少参数,
def get_e(e, user_id='0', request='0',name = '0'):
try:
# 直接把request对象传过来即可
if request != '0':
try:
request_msg = json.dumps(request.POST.dict())
except Exception as e:
request_msg = '获取参数错误'
msg = '\n发生错误的用户:' + str(user_id) + \
'\n请求参数:' + str(request_msg) + \
'\n接口名称:' + str(name) + \ # name = str(self.__class__)获取这个请求所在的类名
'\n发生错误的文件:' + str(e.__traceback__.tb_frame.f_globals['__file__']) + '\n' + \
'错误所在的行号:' + str(e.__traceback__.tb_lineno) + '\n' + \
'错误信息:' + str(e)
# 将得到的错误信息拼接,返回字符串可以直接打印在日志中
return msg
except Exception as e:
return str(e)
代码发生错误后,打印msg的话,会输出如下信息:
发生错误的用户:1163
请求参数:{"format": "json", "comment_if": "0", "user_id": "1163", }
接口名称:<class 'center.views1.MyCmments'>
发生错误的文件:/home/zkjy/apps/center/views1.py
错误所在的行号:48
错误信息:invalid literal for int() with base 10: 'sdf'