Django Logging & Exceptions

Django supports testing activities like logging, debugging, and exception handling. We can capture error logs at various severity levels in text format under a log file.

Django Logging

Django can capture and classify logs using the Python logging module. A log file has elements like Log_level: Logger_name: Message.

Logging configuration consists of four parts:

  • Loggers: It is like an entry point of logging configuration. Loggers are named buckets in which messages can be written.
  • There are levels of logging that define the severity of the message:
  • DEBUG: It captures low-level and verbose system information for debugging purposes. Logging level DEBUG can also be applied with the value 10.
  • INFO: It captures general system information. Logging level INFO can also be applied with a value 20.
  • WARNING: It captures information describing a minor problem or warning. Logging level WARNING can also be applied with a value 30.
  • ERROR: It captures information describing a major problem in a code structure. Logging level ERROR can also be applied with a value 40.
  • CRITICAL: It captures information describing a critical or fatal problem. Logging level CRITICAL can also be applied with a value 50.
  • Handlers: It determines what happens to each message in a logger.
  • Filters: A filter can provide additional control over which log records need to be passed from logger to handler.
  • Formatters: A log record is finally rendered as text. Formatters do the formatting of python objects into text.

To implement logging, simply write the code below in settings.py

LOGGING = {
        'version': 1,
        'disable_existing_loggers':False,
        'handlers':{
            'console':{
                'class':'logging.StreamHandler',
            },
            'file':{
                'class':'logging.FileHandler',
                'filename':'programink.log',
            },
        },
        'root':{
            'handlers':['console', 'file'],
            'level':'DEBUG',
        },
    }
                                

Django Exceptions

Exceptions is Django are as below:

  • AppRegistryNotReady
  • ObjectDoesNotExist
  • EmptyResultSet
  • FieldDoesNotExist
  • MultipleObjectsReturned
  • SuspiciousOperation
  • PermissionDenied
  • ViewDoesNotExist
  • MiddlewareNotUsed
  • ImproperlyConfigured
  • FieldError
  • ValidationError
  • UnreadablePostError
  • TransactionManagementError
  • DatabaseError
  • IntegrityError
  • DataError
  • Resolver404
  • NoReverseMatch