Django log module logging configuration details

  • 2020-05-26 09:28:11
  • OfStack

preface

Django is very perfect for log output information, request information, setting configuration, trackback information, 1 is available, enough for our debugging. But the online environment, if the user sees this information, is very insecure (exposed code). So we're going to turn Debug off online, but we can't throw away the debugging information, so we're going to use the logging module.

The logging module is actually a module of Python, and there is a lot of localization support in Django.

Understand Logger

The first thing to understand about logging is that there are four main things in it: the formatter formatter, the filter filter, the processor handler, and the log instance logger.

Processing flow


   formatter
logger ----> handler ----------------> files, emails
    filter

The process goes like this. First, in the code. We get an instance of logger, and we use that instance to record information.


# import the logging library
import logging
 
# Get an instance of a logger
logger = logging.getLogger('django')
 
def my_view(request, arg1, arg):
 ...
 if bad_mojo:
 # Log an error message
 logger.error('Something went wrong!')

Then, the logger with the name django will pass the information to the corresponding handler, handler will process the information with formater and filter and submit it to log (save to a file, database, or send an email).

1 generally speaking, handler can be send_email, error_file, etc., and handler can be reused in logger. For example, our django processor USES send_email, error_file, request processor USES error_file, info_file two processors, logger and handler can be understood as many-to-many relationship, hee hee.

Configuration mode

Python can be configured in a variety of formats, such as.conf,.ini, etc.

In Django, we are writing the configuration for logging to settings. The corresponding configuration and explanation are as follows (for reference only).


# Administrator mailbox 
ADMINS = (
 ('laixintao','*******@163.com'),
)
 
# Not empty link, but occurs 404 Error, send notification MANAGERS
SEND_BROKEN_LINK_EMAILS = True
MANAGERS = ADMINS
 
#Email Set up the 
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST= 'smtp.163.com'#QQ email SMTP The server ( The mailbox needs to be opened. SMTP service )
EMAIL_PORT= 25 #QQ email SMTP Service port 
EMAIL_HOST_USER = '**********@163.com' # My email account 
EMAIL_HOST_PASSWORD = '**************' # Authorization code 
EMAIL_SUBJECT_PREFIX = 'website' # Prefix the subject line of the message , The default is '[django]'
EMAIL_USE_TLS = True # Open secure links 
DEFAULT_FROM_EMAIL = SERVER_EMAIL = EMAIL_HOST_USER # Set sender 
 
#logging The log configuration 
LOGGING = {
 'version': 1,
 'disable_existing_loggers': True,
 'formatters': {# Log format  
 'standard': {
  'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s'} 
 },
 'filters': {# The filter 
 'require_debug_false': {
  '()': 'django.utils.log.RequireDebugFalse',
  }
 },
 'handlers': {# The processor 
 'null': {
  'level': 'DEBUG',
  'class': 'logging.NullHandler',
 },
 'mail_admins': {# Send email notification to administrator 
  'level': 'ERROR',
  'class': 'django.utils.log.AdminEmailHandler',
  'filters': ['require_debug_false'],#  Only when the  DEBUG = False  Send the email when 
  'include_html': True,
 },
 'debug': {# Log to a log file ( You need to create the corresponding directory or you will get an error )
  'level':'DEBUG',
  'class':'logging.handlers.RotatingFileHandler',
  'filename': os.path.join(BASE_DIR, "log",'debug.log'),# Log output file 
  'maxBytes':1024*1024*5,# The file size  
  'backupCount': 5,# Backup copies 
  'formatter':'standard',# Use which formatters Log format 
 },
 'console':{# Output to console 
  'level': 'DEBUG',
  'class': 'logging.StreamHandler',
  'formatter': 'standard',
 },
 },
 'loggers': {#logging manager 
 'django': {
  'handlers': ['console'],
  'level': 'DEBUG',
  'propagate': False 
 },
 'django.request': {
  'handlers': ['debug','mail_admins'],
  'level': 'ERROR',
  'propagate': True,
 },
 #  For not  ALLOWED_HOSTS  Request does not send error message 
 'django.security.DisallowedHost': {
  'handlers': ['null'],
  'propagate': False,
 },
 } 
}

In the configuration file above, there are three log handlers. Respectively is:

'django.request' : django's request occurs and error is automatically logged, then debug is used to record the information to the file, and mail_admins sends the information to the administrator via email. Email is great here! Instead of a plain text message, it's an html file that looks exactly like the error page we saw in the browser! To use the mail function properly, configure the sender information above as I did 1. I directly went to netease to apply for a mailbox. 3 points to pay special attention to: 1.1 must go to the mail service provider to open SMTP service; 2. Different email service providers may have some special Settings, such as netease, which will give you a client authorization code, which is the password, not the login password of the web page. 3. Notice if the service provider has any restrictions on the frequency of sending messages. 'django' : output the information using the console processor. This processor can be used at development time (what? print? That's too much! See the comments for the last processor.

Finally, don't forget to give the path of the log permission to respond. For example, Apache2 server, you need to give www-data write permission:


sudo chown -R [yourname]:www-data [log]
sudo chmod -R g+s [log]

conclusion

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: