django Explanation of Exception Capture and Log System Procedures

  • 2021-07-22 10:45:24
  • OfStack

The content of this 1 block is very small, the exception can be used try except, and the log only needs a few lines of configuration.

Use the decorator to catch all exceptions within the method

I use a decorator to wrap a method in its entirety, capture all exception information in the method, and convert it to json and return it to the client.


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 = " Exception caught "
      # x = type(e)
      #
      # if x == ValueError:
      #   string = " Numerical conversion exception :" + str(e)
      return JsonError(error_string=str(e), code=code)

  return nefen

JsonError is a previously written json tool.

The decorator is used as follows.


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)

Log configuration


#  Create the log storage path first .
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'), # Or write the path directly: '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'), # Or write the path directly: 'c:\logs\all.log',
      'maxBytes': 1024*1024*5, # 5 MB
      'backupCount': 5,
      'formatter':'standard',
    },
  },
  # DEBUG( Test environment ) CRITICAL( Project collapse )  ERROR( Throw exception not caught ) WARNING( For example 403) INFO( Systematic performance correlation )
  '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',
    },
  },
}

Log configuration consists of three parts

1. Log format formatters

2. Log processing methods, such as saving to an xxx. log file or something, and even sending e-mail automatically.

3. Logger, which is the official application, you can get 1 log and add log content manually.

1 example of writing content to log file


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)

So far 1 django project required components are basically complete. The rest of the work is to write business logic.


Related articles: