Getting Started with Django Logging in 5 Minutes

Getting Started with Django Logging in 5 Minutes

Setting up Django logging can sometimes be a little complex, so here are the no-nonsense steps required to make a new Django 1.5 instance log to a file without hassles. We’re going to look at each of the 4 components of Django logging:

  1. Loggers: a logger is the object that we will use to pass messages to the logging system
  2. Handlers: the handler is an engine that determines what to do with a message when it is recieved from the logger
  3. Filters: allow you to restrict the type of messages that are sent from the logger to the handler
  4. Formatters: describe the text representation of the log message

Simple, right? For more information, check out the Django documentation on logging.

Setting up your Project for Logging

Logging configuration is specified in your project’s settings.py file. Let’s go through each of the four components from bottom to top, one-by-one and explain what we’re going to do.

Formatters

First let’s declare the format that we can log entries in. I’m going to use two formats, verbose and simple:

'formatters': {
       
       
        'verbose': {
       
       
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
       
       
            'format': '%(levelname)s %(message)s'
        },
    },
Python

Filters

In my example, I don’t want to filter anything. But if I did my filters would look like so:

'filters': {
       
       
        'special': {
       
       
            '()': 'project.logging.SpecialFilter',
            'foo': 'bar',
        }
    },
Python

This defines one filter, project.logging.SpecialFilter, using the alias special. In this case, the argument foo will be given a value of bar when instantiating the SpecialFilter.

Handlers

This is where it gets fun. Now we’re going to tell Django to log all of our output messages to a file:

'handlers': {
       
       
        'file': {
       
       
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
        },
    },
Python

level means to log anything DEBUG or higher (which includes all levels) with this handler.

Loggers

Finally, we will declare two loggers to be used, one for the django core and one for your application:

'loggers': {
       
       
        'django': {
       
       
            'handlers':['file'],
            'propagate': True,
            'level':'DEBUG',
        },
        'MYAPP': {
       
       
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }
Python

Replace MYAPP with the name of your application to test things out.

扫描二维码关注公众号,回复: 11976797 查看本文章

Full Project Configuration

According to the above, we should now have a logging config in settings.py that looks like this:

# settings.py
LOGGING = {
       
       
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
       
       
        'verbose': {
       
       
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
       
       
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
       
       
        'file': {
       
       
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
       
       
        'django': {
       
       
            'handlers':['file'],
            'propagate': True,
            'level':'DEBUG',
        },
        'MYAPP': {
       
       
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }
}
Python

Testing Logging

Let’s go to our views.py file and create some new functions that use logging:

# views.py
import logging
logger = logging.getLogger(__name__)
 
def myfunction():
    logger.debug("this is a debug message!")
 
def myotherfunction():
    logger.error("this is an error message!!")
Python

Now we’ll use the shell to call these functions.

>>> from polls.views import *
>>> myfunction()
>>> myotherfunction()
Python console session

And here is the output in our mysite.log file:

[16/Apr/2013 09:49:38] DEBUG [polls.views:7] this is a debug message!
[16/Apr/2013 09:49:46] ERROR [polls.views:10] this is an error message!!
Bash

Next Steps

If you have a complex project with multiple applications, you can create multiple handlers with different file names to have multiple log files. As always, read the docs and good luck!

猜你喜欢

转载自blog.csdn.net/niekunhit/article/details/50247779