How to customize logging in Django?

One common way to customize logging in Django is by configuring the logging module to define the format, level, and output method of the logs.

  1. the configuration file settings.py
  2. The action of recording activity or events in a detailed and systematic way is known as logging.
  3. recording/logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'custom_logger': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '/path/to/logfile.log',
            'maxBytes': 1024*1024*5,  # 5MB
            'backupCount': 5,
            'formatter': 'custom_formatter',
        },
    },
    'formatters': {
        'custom_formatter': {
            'format': '[%(asctime)s] %(levelname)s %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S',
        },
    },
    'root': {
        'handlers': ['custom_logger'],
        'level': 'DEBUG',
    },
}

In the above configuration, we have defined a handler named custom_logger that writes logs to a specified file located at /path/to/logfile.log. The handler’s level is set to DEBUG, indicating that it will log all levels of messages. The maxBytes parameter defines the maximum size of the log file, and when it is exceeded, the file will automatically be split and backed up. The backupCount parameter specifies the number of backup files to keep. The custom_formatter is a customized log format that includes the date, log level, and message.

  1. In the root configuration section, add the custom_logger handler to the handlers list and set the level to DEBUG, indicating that the root logger will use this handler.
  2. The processor can be used in other loggers elsewhere as required. For example:
import logging

logger = logging.getLogger('myapp')
logger.addHandler(logging.handlers['custom_logger'])
logger.setLevel(logging.DEBUG)

In the above example, we are getting the logger named myapp and adding the custom_logger handler to it, setting the level to DEBUG.

In this way, the customization of Django logging configuration is completed, allowing for modifications to the logging handler, format, and level based on actual requirements.

bannerAds