django 捕獲異常和日志系統(tǒng)過程詳解
這一塊的內(nèi)容很少, 異常使用try except即可, 日志只需要幾行配置.
使用裝飾器捕獲方法內(nèi)的所有異常
我使用裝飾器來整個(gè)包裹一個(gè)方法, 捕獲方法中的所有異常信息.并將其轉(zhuǎn)為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 = "數(shù)值轉(zhuǎn)換異常:" + 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)
日志配置
# 首先創(chuàng)建日志存儲(chǔ)路徑.
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(測(cè)試環(huán)境) CRITICAL(項(xiàng)目崩潰) ERROR(拋出異常未被捕獲) WARNING(例如403) INFO(系統(tǒng)表現(xiàn)相關(guān))
'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文件或者別的什么, 甚至可以自動(dòng)發(fā)送電子郵件.
3.日志器, 也就是正式的應(yīng)用, 你可以獲取一個(gè)log, 手動(dòng)添加log內(nèi)容.
一個(gè)向log文件寫入內(nèi)容的例子
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)
至此一個(gè)django項(xiàng)目所需要的組成部分基本齊全了. 剩下的工作只是業(yè)務(wù)邏輯的編寫.
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python中deepcopy的用法及注意事項(xiàng)詳細(xì)解釋
這篇文章主要介紹了Python中deepcopy用法及注意事項(xiàng)的相關(guān)資料,deepcopy是Python中用于創(chuàng)建對(duì)象深拷貝的函數(shù),與淺拷貝不同,它會(huì)遞歸地復(fù)制對(duì)象及其所有子對(duì)象,確保新對(duì)象是獨(dú)立的副本,需要的朋友可以參考下2025-04-04
總結(jié)Python編程中函數(shù)的使用要點(diǎn)
這篇文章主要介紹了Python編程中函數(shù)的使用要點(diǎn)總結(jié),文中也講到了人民群眾喜聞樂見的lambda表達(dá)式的用法,需要的朋友可以參考下2016-03-03
10個(gè)Python常用的損失函數(shù)及代碼實(shí)現(xiàn)分享
損失函數(shù)是一種衡量模型與數(shù)據(jù)吻合程度的算法。損失函數(shù)測(cè)量實(shí)際測(cè)量值和預(yù)測(cè)值之間差距的一種方式。本文為大家總結(jié)了10個(gè)常用的損失函數(shù)及Python代碼實(shí)現(xiàn),需要的可以參考一下2022-09-09
淺談Python 命令行參數(shù)argparse寫入圖片路徑操作
這篇文章主要介紹了淺談Python 命令行參數(shù)argparse寫入圖片路徑操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Python使用re模塊實(shí)現(xiàn)信息篩選的方法
這篇文章主要介紹了Python使用re模塊實(shí)現(xiàn)信息篩選的方法,結(jié)合實(shí)例形式分析了Python正則re模塊進(jìn)行信息篩選操作的相關(guān)實(shí)現(xiàn)技巧及相關(guān)函數(shù)使用技巧,需要的朋友可以參考下2018-04-04
python調(diào)用Moxa PCOMM Lite通過串口Ymodem協(xié)議實(shí)現(xiàn)發(fā)送文件
這篇文章主要介紹了python調(diào)用Moxa PCOMM Lite通過串口Ymodem協(xié)議實(shí)現(xiàn)發(fā)送文件,需要的朋友可以參考下2014-08-08

