简体   繁体   中英

What is the best way to write to a log file when an exception is raised in Django?

What is the best way to write to a log file when any exception occurs within the Django app without hardcoding to each function in the view ie middleware?

Eg when DatabaseError,ValueError,Integrity error are raised in the views.

I need something that can be used both in production and development with DRY concept.

import logging

logger = logging.getLogger(__name__)

def my_view(request, arg1, arg):
    ...
    if bad_mojo:
        # Log an error message
        logger.error('Something went wrong!')

You can use Logs .

Here's an example configuration which triggers on WARNING and more important levels.

(Taken from Django 3.0 documentation)

This goes in your settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'WARNING',
            'class': 'logging.FileHandler',
            'filename': '/path/to/django/debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'WARNING',
            'propagate': True,
        },
    },
}

As the level is set to WARNING , three types of levels will trigger the logger, ie WARNING , ERROR and CRITICAL .

Also, we have used django (as logger) to utilize Django's catch-all logger. It will allow us to create a more readable log, as the errors will be properly categorized (like template, database etc) in the logfile. You can read more about them over here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM