django 捕獲異常和日志系統(tǒng)過程詳解
這一塊的內(nèi)容很少, 異常使用try except即可, 日志只需要幾行配置.
使用裝飾器捕獲方法內(nèi)的所有異常
我使用裝飾器來整個包裹一個方法, 捕獲方法中的所有異常信息.并將其轉(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)建日志存儲路徑. 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(測試環(huán)境) CRITICAL(項目崩潰) 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文件或者別的什么, 甚至可以自動發(fā)送電子郵件.
3.日志器, 也就是正式的應(yīng)用, 你可以獲取一個log, 手動添加log內(nèi)容.
一個向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)
至此一個django項目所需要的組成部分基本齊全了. 剩下的工作只是業(yè)務(wù)邏輯的編寫.
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Selenium向iframe富文本框輸入內(nèi)容過程圖解
這篇文章主要介紹了Selenium向iframe富文本框輸入內(nèi)容過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04

Python操作Sonqube API獲取檢測結(jié)果并打印過程解析

Django的models中on_delete參數(shù)詳解

python機(jī)器學(xué)習(xí)理論與實戰(zhàn)(五)支持向量機(jī)