Apr 29, 2017 Djnago 中文版
Django is a popular web framework written in Python, and it provides an elegant mechanism for logging. But it might be a little bit complicated if you’re new to Django. Thus, this post is about how to configure logging settings for you application.
If you have not created a proper environment for the following steps, you can use below commands:
# Install Django
python -m pip install Django
# Check Django's version
python -m django --version
# Create a new Django project
django-admin startproject <project-name>
The structure of your project should look like this:
project-name/
├── project-name
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
Before we dive into logging, get some basic information. When using the command django-admin startproject to create a project, logging settings won’t be automatically added. So, we have to manually add it into settings.py. Here is a simple example:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
# TODO
},
'handlers': {
# TODO
},
'loggers': {
# TODO
},
'filters': {
# TODO
},
}
As a beginner, let’s just focus on formatters, handlers and loggers for now.
Below is a picture describing their relationships:
Ok, let’s continue to complete each part. In formatters, we need specify formats like below:
'formatters': {
'your-formatter': {
'()': 'django.utils.log.ServerFormatter',
'format': '[%(asctime)s] %(message)s',
}
},
As you see, I defined a simple string format ( [%(asctime)s] %(message)s ) :
The output would look like this:
[2017-04-26 11:07:33,380] Your message is here
Of course, there are more options we can use. Check here.
Here is an example for setting handlers:
'handlers': {
'web': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/path/to/your-web.log',
'formatter': 'your-formatter'
},
'other_service': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/path/to/your-other-service.log',
'formatter': 'your-formatter'
},
},
I defined two handlers for different tasks, and these handlers will create two different log files in different places.
Visit here to get more details.
An example for setting loggers:
'loggers': {
'your-logger': {
'handlers': ['web'],
'level': 'DEBUG',
'propagate': True,
},
},
I’m not going to talk about propagate here because it needs more time to elaborate. But you can have a basic understanding of it by reading this.
After we finished setting up logging, it’s time to use it in your Python scripts:
# Use logging library
import logging
# Get an instance of a logger
logger = logging.getLogger('your-logger')
# Log a message
logger.info('Your message is here.')
If you have any suggestions, questions or even find some typos, feel free to contact me. Thank you! :)
zeckli.devforgalaxy@gmail.com © 2015-2019 zeckli, thanks to Jekyll and GitHub.