Insights

10 Django Logging Best Practices

Django logging best practices are essential for every Django developer. In this article, we'll go over 10 of the most important ones.

Logging is an important part of any web application. It can be used for debugging, monitoring, and auditing. When done correctly, logging can be a valuable tool for understanding what is happening in your application.

Django provides a logging framework that allows you to emit log records to a variety of destinations. In this article, we will discuss 10 best practices for using the Django logging framework.

1. Logging levels

Logging levels give you the ability to specify the importance or severity of a log message. There are six logging levels in Python’s logging module, from least severe to most: DEBUG, INFO, WARNING, ERROR, CRITICAL, and FATAL.

You can set the logging level for your Django project in the settings.py file. By default, the logging level is set to DEBUG, which means all messages will be logged. But in a production environment, you’ll want to set the logging level to ERROR so that only error messages are logged.

Here’s an example of how to set the logging level in settings.py:

LOGGING = {
‘version’: 1,
‘disable_existing_loggers’: False,
‘handlers’: {
‘console’: {
‘class’: ‘logging.StreamHandler’,
},
},
‘loggers’: {
‘django’: {
‘handlers’: [‘console’],
‘level’: ‘ERROR’,
},
},
}

As you can see, we’ve specified that the logging level for the ‘django’ logger is ‘ERROR’. This means that only error messages will be logged when the Django server is running in production.

Of course, you can also set the logging level for individual app loggers. For example, if you have an app called ‘myapp’, you can set the logging level for just that app like this:

LOGGING = {
‘version’: 1,
‘disable_existing_loggers’: False,
‘handlers’: {
‘console’: {
‘class’: ‘logging.StreamHandler’,
},
},
‘loggers’: {
‘django’: {
‘handlers’: [‘console’],
‘level’: ‘ERROR’,
},
‘myapp’: {
‘handlers’: [‘console’],
‘level’: ‘DEBUG’,
},
},
}

Now the logging level for the ‘myapp’ logger is

2. Use the standard library logging module

The standard library logging module is part of the Python standard library, which means it’s always available, even when you’re using third-party libraries that don’t play well with Django.

It’s also battle-tested and well-documented. The Django community has standardized on using the standard library logging module, so there are lots of resources available if you need help.

Finally, the standard library logging module is very flexible. It lets you do things like send your logs to different places (e.g. files, emails, databases) depending on their severity, and gives you lots of control over how your logs are formatted.

3. Don’t log too much

If you log too much information, your logs will be hard to read and it will be difficult to find the information you’re looking for. In addition, if you log too much information, your logging system will quickly become overloaded and start to slow down your website.

Therefore, it’s important to only log the information that you need, and to make sure that your logging system is able to handle the amount of information you’re logging.

4. Don’t log too little

If you don’t log enough information, it will be difficult to debug errors when they occur. You won’t have enough data to troubleshoot the issue, and you’ll likely have to add more logging statements to your code later. It’s better to err on the side of logging too much information than too little.

Of course, you don’t want to log so much information that your logs are cluttered and difficult to read. Strike a balance between logging too little and too much, and make sure your logs are easily readable.

5. Be consistent with your formatting

When you’re looking at a log file, you want to be able to quickly scan and find the information you need. This is only possible if the format of the logs is consistent. Imagine trying to find a specific log entry in a file that contains entries in multiple different formats. It would be very difficult and time-consuming.

Therefore, it’s important to choose a format for your logs and stick with it. A good format is one that is easy to read and includes all the relevant information. For example, you might want to include the date, time, level, module, and message in each log entry.

6. Use a third-party package for emailing errors

When an error occurs in your Django application, the traceback is emailed to the ADMINS setting. By default, this just prints the email to the console. If you want the emails to actually be sent, you need to configure a mail server.

This can be a hassle to set up, and it’s easy to get wrong. A better option is to use a third-party package like django-sentry or loggly. These services will take care of everything for you, and they offer other features like search and analytics that can be really helpful.

7. Use a third-party package for monitoring exceptions

When an exception is raised, Django will log it to the standard error stream. However, this information is often lost in the noise of other messages that are being logged. A third-party package can help you filter and monitor exceptions so you can fix them quickly.

There are many different options available, but Sentry is a popular choice. It’s free for open source projects, and it has a paid plan for private projects.

Once you’ve set up Sentry, you can configure Django to send exceptions to Sentry instead of logging them to the standard error stream. To do this, add the following code to your settings.py file:

LOGGING = {
‘version’: 1,
‘disable_existing_loggers’: True,
‘root’: {
‘level’: ‘WARNING’,
‘handlers’: [‘sentry’],
},
‘formatters’: {
‘verbose’: {
‘format’: ‘%(levelname)s %(asctime)s %(module)s ‘
‘(process:%(process)d line:%(lineno)d) %(message)s’
},
},
‘handlers’: {
‘sentry’: {
‘level’: ‘ERROR’, # To capture more than ERROR, change to WARNING, INFO, or DEBUG
‘class’: ‘raven.contrib.django.raven_compat.handlers.SentryHandler’,
‘tags’: {‘custom-tag’: ‘x’},
},
‘console’: {
‘level’: ‘DEBUG’,
‘class’: ‘logging.StreamHandler’,
‘formatter’: ‘verbose’
}
},
‘loggers’: {
‘django.db.backends’: {
‘level’: ‘ERROR’,
‘handlers’: [‘console’],
‘propagate’: False,
},
‘raven’: {
‘level’: ‘DEBUG’,
‘handlers’: [‘console’

8. Use a third-party package for viewing logs

The default Django logging configuration is very basic. It doesn’t allow for much customization, and it’s not easy to view logs in a user-friendly way. A third-party logging package will give you more control over your logging configuration and make it easier to view your logs.

There are many different logging packages available for Django, so it’s important to choose one that’s well-maintained and has good documentation. One popular option is django-logging-json, which allows you to view your logs in JSON format.

Another option is Graylog, which is a full-featured logging platform that can be used with Django. Graylog provides a web interface for viewing and searching logs, as well as an API for integrating with other applications.

9. Create custom loggers

By default, Django uses the root logger to log all messages at the DEBUG level or higher. This is fine for development, but in production, you’ll want more control over what’s logged and where it’s logged.

Creating custom loggers gives you that control. You can specify the name of the logger, the level at which it should log messages, and where those messages should go (e.g., to a file, to email, to a database, etc.).

When creating custom loggers, be sure to use descriptive names so you can easily identify them later. For example, if you have a logger for your website’s contact form, you might name it “website.contact_form”.

10. Write tests to ensure that you’re logging correctly

If you’re not logging correctly, then it’s very difficult to debug errors in your code. By writing tests, you can be sure that you’re logging the right information at the right time, and in the right format.

Not only will this save you time in the long run, but it will also help you build a more robust and reliable logging system.

Previous

10 AWS Workspaces Security Best Practices

Back to Insights
Next

10 Journal Entry Approval Best Practices