0

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 i.e. middleware?

E.g. 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!')
csandreas1
  • 2,026
  • 1
  • 26
  • 48

1 Answers1

1

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, i.e. 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.

Swetank Poddar
  • 1,257
  • 9
  • 23