Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integration with Django #27

Open
RobertoMaurizzi opened this issue May 8, 2024 · 0 comments
Open

Integration with Django #27

RobertoMaurizzi opened this issue May 8, 2024 · 0 comments

Comments

@RobertoMaurizzi
Copy link

RobertoMaurizzi commented May 8, 2024

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant