Custom Log Formatter

A snippet showing how to use custom formatters in Django logs.


# settings.py

import logging

class CustomJsonFormatter(logging.Formatter):
    def format(self, record):
        import json
        log_record = {
            "ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%S"),
            "lvl": record.levelname,
            "logger": record.name,
            "msg": record.getMessage(),
            "pathname": record.pathname,
            "lineno": record.lineno,
        }
        return json.dumps(log_record)

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "json": {
            '()': CustomJsonFormatter,
        },
        "colored": {
            "format": "\x1b[1;32m[{asctime}] {levelname:<8}\x1b[0m \x1b[36m{module}:{lineno}\x1b[0m {message}",
            "style": "{",
            "datefmt": "%Y-%m-%d %H:%M:%S",
        },
    },
    "handlers": {
        "console_json": {
            "class": "logging.StreamHandler",
            "formatter": "json"
        },
        "console_colored": {
            "class": "logging.StreamHandler",
            "formatter": "colored"
        },
    },
    "root": {"handlers": ["console_colored"], "level": "INFO"},
}
      
Explanation:
  • Real JSON formatters are available via third-party libs if you need strict JSON.
  • Real JSON formatters are available via third-party libs if you need strict JSON.
  • Category Logging
  • Total Views 836
  • Last Modified 03 June, 2026
  • Tags #logging #formatter #custom #debug
Previous snippet
Log Database Queries
Next snippet
Set a Session Variable
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.