django 捕获异常和日志系统过程详解
作者:行如风 时间:2022-04-26 22:12:43
这一块的内容很少, 异常使用try except即可, 日志只需要几行配置.
使用装饰器捕获方法内的所有异常
我使用装饰器来整个包裹一个方法, 捕获方法中的所有异常信息.并将其转为json返回客户端.
import functools
def catch_exception(func, code=500, *args, **kwargs):
'''
:param func:
:return:
'''
@functools.wraps(func, *args, **kwargs)
def nefen(request, *args, **kwargs):
try:
back = func(request, *args, **kwargs)
return back
except Exception as e:
# string = "捕获到异常"
# x = type(e)
#
# if x == ValueError:
# string = "数值转换异常:" + str(e)
return JsonError(error_string=str(e), code=code)
return nefen
JsonError是之前编写的json工具.
装饰器的使用方法如下.
class ReturnJson(APIView):
coreapi_fields=(
DocParam("token"),
)
@catch_exception
def get(self, request, *args, **kwargs):
params=get_parameter_dic(request)
return JsonResponse(data=params)
@catch_exception
def post(self, request, *args, **kwargs):
params=get_parameter_dic(request)
return JsonResponse(data=params)
@catch_exception
def put(self, request, *args, **kwargs):
params=get_parameter_dic(request)
return JsonResponse(data=params)
日志配置
# 首先创建日志存储路径.
import logging
import django.utils.log
import logging.handlers
log_path = os.path.join(BASE_DIR, "logs")
if not os.path.exists(log_path):
os.makedirs("logs")
# DJANGO_LOG_LEVEL=DEBUG
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
'standard': {
'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(levelname)s]- %(message)s'
},
},
'handlers': {
'default': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_DIR,'logs','all.log'), #或者直接写路径:'c:\logs\all.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'standard',
},
'file': {
'level':'INFO',
'class':'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_DIR, 'logs','debug.log'), #或者直接写路径:'c:\logs\all.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
},
# DEBUG(测试环境) CRITICAL(项目崩溃) ERROR(抛出异常未被捕获) WARNING(例如403) INFO(系统表现相关)
'loggers': {
'print': {
'handlers': ["file"],
'level': 'INFO',
'propagate': False
},
'ifacerecognition': {
'handlers': ['default'],
'level': 'ERROR',
},
# 'django': {
# 'handlers': ['default'],
# 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
# },
'django.request': {
'handlers': ['default'],
'level': 'ERROR',
},
},
}
日志配置由三部分组成
1.日志格式formatters
2.日志处理方法, 例如保存到xxx.log文件或者别的什么, 甚至可以自动发送电子邮件.
3.日志器, 也就是正式的应用, 你可以获取一个log, 手动添加log内容.
一个向log文件写入内容的例子
import logging
class ReturnJson(APIView):
coreapi_fields=(
DocParam("token"),
)
@catch_exception
def get(self, request, *args, **kwargs):
params=get_parameter_dic(request)
log=logging.getLogger("print")
log.info("asdf")
log.error("asdffff")
return JsonResponse(data=params)
至此一个django项目所需要的组成部分基本齐全了. 剩下的工作只是业务逻辑的编写.
来源:https://www.jianshu.com/p/04287164a274
标签:django,捕获,异常,日志,系统
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
人脸识别实战之Opencv+SVM实现人脸识别
2021-01-06 09:32:13
![](https://img.aspxhome.com/file/2023/5/72775_0s.png)
建立合理的索引提高SQL Server的性能
2009-01-23 14:44:00
常用的Python代码调试工具总结
2023-05-17 19:24:29
![](https://img.aspxhome.com/file/2023/2/112612_0s.png)
python实现朴素贝叶斯分类器
2022-12-05 03:35:50
python logging 日志的级别调整方式
2021-09-15 10:08:29
Django haystack实现全文搜索代码示例
2021-11-08 05:31:36
three.js中文文档学习之创建场景
2023-08-22 21:02:00
Python实现图片指定位置加图片水印(附Pyinstaller打包exe)
2023-08-13 04:27:16
![](https://img.aspxhome.com/file/2023/5/94065_0s.jpg)
SQL Server转换为XQuery及反向转换
2009-01-20 13:32:00
python工具快速为音视频自动生成字幕(使用说明)
2021-04-14 15:15:26
解决python3 HTMLTestRunner测试报告中文乱码的问题
2021-10-19 04:34:06
Python GUI布局工具Tkinter入门之旅
2021-11-08 14:38:23
![](https://img.aspxhome.com/file/2023/1/118531_0s.jpg)
python的函数形参和返回值你了解吗
2021-10-26 05:49:28
SQL Server如何保证可空字段中非空值唯一
2011-02-24 16:44:00
Oracle SQL性能优化系列学习二
2010-07-23 13:23:00
垂直栅格与渐进式行距(上)
2009-04-01 18:30:00
Python教程之pytest命令行方式运行用例
2022-08-01 22:08:06
![](https://img.aspxhome.com/file/2023/1/81531_0s.png)
提高MySQL查询效率的三个技巧
2009-02-11 13:19:00
python Tensor和Array对比分析
2023-08-27 04:37:02
python实现斐波那契递归函数的方法
2022-03-22 19:54:49