Configuration and processing of Django log Logging

Source: Internet
Author: User

Logs are indispensable in program development. Through logs, we can analyze the errors and exceptions. It is useful in a production environment. Third-party components such as log4j and logback are commonly used in Java development. So how does one process logs in Django? Django uses the logging module provided by python. However, to use logging in Django, you must set certain configuration rules in setting.

  1. Logging Module

The logging module provides flexible means for applications to record events, errors, warnings, and debugging information. This information can be collected, filtered, written to a file, sent to a system log, or even sent to a remote computer over the network.

> Log record level

The focus of the logging module is to generate and process log messages. Each message is composed of some texts and relevant levels that indicate its severity. The level contains the symbol name and number value.

Level Value Description
Critical 50 Critical errors/messages
Error 40 Error
Warning 30 Warning Message
Info 20 Notification Message
Debug 10 Debugging
Notset 0 No Level

> Recorder

The recorder is responsible for managing the default behavior of log messages, including the log record level, output target location, message format, and other basic details.

Keyword Parameter Description
Filename Attaches a log message to a file with the specified file name
Filemode Specifies the file opening mode.
Format Format String used to generate log messages
Datefmt Format String used to output the date and time
Level Set the recorder level
Stream Open files are provided to send log messages to files.

> Format: Log message format

Format Description
% (Name) S Recorder name
% (Levelno) S Digital log record level
% (Levelname) S Log-level text name
% (Filename) S Execute the log to record the name of the called source file
% (Pathname) S Execute the log to record the path name of the called source file
% (Funcname) S Name of the function called by the execution log record
% (Module) S Name of the module that executes the log record call
% (Lineno) S

Line number of the invocation log record call

% (Created) S Execution time of log records
% (Asctime) S Date and Time
% (Msecs) S Millisecond
% (Thread) d Thread ID
% (Threadname) S Thread name
% (Process) d Process ID
% (Message) S Recorded Message

> Built-in Processors

The logging module provides some processors that can process log messages in various ways. Add these processors to the logger object using the addhandler () method. You can also configure its own filtering and level for each processor.

Handlers. datagramhandler (host, Port): sends a log message to the UDP server located on the specified host and port.

Handlers. filehandler (filename): Write log messages to the file filename.

Handlers. httphandler (host, URL): use http get or post methods to upload log messages to an HTTP server.

Handlers. rotatingfilehandler (filename): Write log messages to the file filename. If the file size exceeds the value specified by maxbytes, it is backed up as filename1.

Because there are many built-in processors, if you want to learn more. You can view the official manual.

2. Django uses logging to record logs

Now I understand how to use logging. Now I can use it with Django.

> Configure the setting. py configuration file

# Import loggingimport Django. utils. logimport logging. handlerslogging = {'version': 1, 'Disable _ existing_loggers ': True, 'formatters': {'standard': {'format': '% (asctime) s [% (threadname) S: % (thread) D] [% (name) S: % (lineno) D] [% (module) S: % (funcname) s] [% (levelname) S]-% (Message) s '} # log format}, 'filters' :{}, 'handlers': {'mail _ admins ': {'level': 'error', 'class': 'django. utils. log. adminemailhandler ', 'include _ HTML': True,}, 'default': {'level': 'debug', 'class': 'logging. handlers. rotatingfilehandler ', 'filename':'/sourcedns/log/All. log', # log output file 'maxbytes ': 1024*1024*5, # file size 'backupcount': 5, # Number of backup copies 'formatter': 'standard ', # formatters log format}, 'error': {'level': 'error', 'class': 'logging. handlers. rotatingfilehandler ', 'filename':'/sourcedns/log/error. log', 'maxbytes ': 1024*1024*5, 'backupcount': 5, 'formatter': 'standard',}, 'console': {'level ': 'debug', 'class': 'logging. streamhandler ', 'formatter': 'standard'}, 'request _ handler': {'level': 'debug', 'class': 'logging. handlers. rotatingfilehandler ', 'filename':'/sourcedns/log/script. log', 'maxbytes ': 1024*1024*5, 'backupcount': 5, 'formatter': 'standard',}, 'scprits _ handler': {'level ': 'debug', 'class': 'logging. handlers. rotatingfilehandler ', 'filename':'/sourcedns/log/script. log ', 'maxbytes': 1024*1024*5, 'backupcount': 5, 'formatter ': 'standard', }}, 'loggers': {'django ': {'handlers': ['default', 'console'], 'level': 'debug', 'pagate': false}, 'django. request ': {'handlers': ['request _ handler'], 'level': 'debug', 'pagate': false,}, 'scripts ': {'handlers': ['scprits _ handler'], 'level': 'info', 'pagate': false}, 'sourcedns. webdns. views ': {'handlers': ['default', 'error'], 'level': 'debug', 'pagate': true}, 'sourcedns. webdns. util ': {'handlers': ['error'], 'level': 'error', 'pagate': true }}}


1. formatters: configure the log format for Printing

2. Handler: used to define the specific log processing methods. There are multiple definitions. "default" is the default method, and "console" is the method of printing to the console.

3. Loggers: used to configure handlers to process logs. For example, you need to output logs to files and the console at the same time.


1. The loggers type is "Django", which processes all types of logs.

2. sourcedns. webdns. Views application's py file


> Views. py code configuration

Logger = logging. getlogger ('sourcedns. webdns. views ') # Just now at setting. loggertry: MySQL = connectmysql ('2017. 0.0.1 ', '123', 'David') cannot exception, E: logger. error (e) # directly write the error to the log file

> View log files

650) This. width = 650; "src =" AE /wKiom1O0H_bDjmxGAAFYayONrP0965.jpg "Title =" out.png "alt =" wkiom1o0h_bdjmxgaafyayonrp0965.jpg "/>

Write it here today. In fact, logging has many functions. If you are interested in logging, read the official manual.

This article is from the "System O & M" blog, please be sure to keep this source

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.