Skip to content

Integration with Django #27

@RobertoMaurizzi

Description

@RobertoMaurizzi

To enable logging with traceback_with_variables for Django (and possibly other frameworks) the correct approach is to extend the standard Python logging integration so that it has a custom formatting function that uses traceback_with_variables. For example, in your settings.py you can add:

import traceback_with_variables

class CustomLogFormatter(logging.Formatter):
    def formatException(self, ei):
        return "\n".join(
            traceback_with_variables.iter_exc_lines(
                e=ei[1],
                fmt=traceback_with_variables.Format(
                    custom_var_printers=[
                        ("password", lambda _: "...hidden..."),
                        ("token", lambda _: "...hidden..."),
                    ]
                ),
            ),
        )

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"},
        "custom": {  # <== our custom formatter
            "()": CustomLogFormatter,
            "format": "%(asctime)s %(levelname)s: %(message)s",
        },
    },
    "handlers": {
        "console": {"level": "INFO", "class": "logging.StreamHandler", "formatter": "custom"},
    },
    "loggers": {
        "django": {
            "handlers": ["console"],
            "propagate": True,
        },
        "django.request": {
            "handlers": ["console"],
            "level": "DEBUG",  # change debug level as appropiate
            "propagate": False,
        },
    },
    "root": {
        "handlers": ["console"],
        "level": "DEBUG",
    },
}

(writing this as an issue since I'm not sure where you'd like it in the documentation)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @RobertoMaurizzi

        Issue actions

          Integration with Django · Issue #27 · andy-landy/traceback_with_variables