Home > Java > javaTutorial > body text

Detailed explanation of the configuration of Django log module logging

高洛峰
Release: 2017-02-16 17:01:02
Original
1407 people have browsed it

Logs are indispensable in program development. Through logs, we can analyze where the errors are and what abnormalities there are. It is of great use in production environments. In java development, three-party components such as log4j and logback are usually used. The following article mainly introduces the relevant information of Django log module logging. Friends in need can refer to it.

Preface

Django is very complete in log output information. The request information, setting configuration, and trackback information are all available, which is enough for us to debug. However, in an online environment, it is very unsafe (exposed code) if users are allowed to see this information. Therefore, we need to turn off Debug online, but we cannot throw away the debugging information. This requires the use of the logging module.

The logging module is actually a Python module and has a lot of localized support in Django.

Understanding Logger

First of all, we must understand the work of logging. There are four main things in it: formatter, filter, and processor handler. Log instance logger.

Processing process

   formatter
logger ----> handler ----------------> files, emails
    filter
Copy after login

The processing process is like this. First, in the code. What we get is a logger instance, and we use this 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!')
Copy after login

Then, the logger named django will hand over the information to the corresponding handler. The handler will process the information using formatter and filter, and submit the log ( Save to file, database, or send email).

Generally speaking, the handler can be send_email, error_file and other responsible processing methods, and the handler can be reused in the logger. For example, our Django processor uses two processors, send_email and error_file, and the request processor uses two processors, error_file and info_file. Logger and handler can be understood as a many-to-many relationship, hehe.

Configuration method

You can configure logging in multiple formats in Python, such as .conf, .ini, etc.

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

#管理员邮箱
ADMINS = (
 ('laixintao','*******@163.com'),
)
 
#非空链接,却发生404错误,发送通知MANAGERS
SEND_BROKEN_LINK_EMAILS = True
MANAGERS = ADMINS
 
#Email设置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST= 'smtp.163.com'#QQ邮箱SMTP服务器(邮箱需要开通SMTP服务)
EMAIL_PORT= 25 #QQ邮箱SMTP服务端口
EMAIL_HOST_USER = '**********@163.com' #我的邮箱帐号
EMAIL_HOST_PASSWORD = '**************' #授权码
EMAIL_SUBJECT_PREFIX = 'website' #为邮件标题的前缀,默认是'[django]'
EMAIL_USE_TLS = True #开启安全链接
DEFAULT_FROM_EMAIL = SERVER_EMAIL = EMAIL_HOST_USER #设置发件人
 
#logging日志配置
LOGGING = {
 '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'} 
 },
 'filters': {#过滤器
 'require_debug_false': {
  '()': 'django.utils.log.RequireDebugFalse',
  }
 },
 'handlers': {#处理器
 'null': {
  'level': 'DEBUG',
  'class': 'logging.NullHandler',
 },
 'mail_admins': {#发送邮件通知管理员
  'level': 'ERROR',
  'class': 'django.utils.log.AdminEmailHandler',
  'filters': ['require_debug_false'],# 仅当 DEBUG = False 时才发送邮件
  'include_html': True,
 },
 'debug': {#记录到日志文件(需要创建对应的目录,否则会出错)
  'level':'DEBUG',
  'class':'logging.handlers.RotatingFileHandler',
  'filename': os.path.join(BASE_DIR, "log",'debug.log'),#日志输出文件
  'maxBytes':1024*1024*5,#文件大小 
  'backupCount': 5,#备份份数
  'formatter':'standard',#使用哪种formatters日志格式
 },
 'console':{#输出到控制台
  'level': 'DEBUG',
  'class': 'logging.StreamHandler',
  'formatter': 'standard',
 },
 },
 'loggers': {#logging管理器
 'django': {
  'handlers': ['console'],
  'level': 'DEBUG',
  'propagate': False 
 },
 'django.request': {
  'handlers': ['debug','mail_admins'],
  'level': 'ERROR',
  'propagate': True,
 },
 # 对于不在 ALLOWED_HOSTS 中的请求不发送报错邮件
 'django.security.DisallowedHost': {
  'handlers': ['null'],
  'propagate': False,
 },
 } 
}
Copy after login

There are three log processors in the above configuration file. They are:

  1. 'django.request': Django's request will automatically record errors when they occur, and then use debug to record the information to a file, and mail_admins to send the information to the administrator via email. . The email functionality here is great! It is not a plain text message, but an html file, exactly the same as the error page we see in the browser! To use the email function normally, you need to configure the above email sender information like I did. I went directly to NetEase to apply for an email address. Pay special attention to three points: 1. Be sure to go to the email service provider to enable the SMTP service; 2. Different email service providers may have some special settings. For example, NetEase will give you a client authorization code, which is the password, and It is not the login password for the web page. 3. Pay attention to whether the service provider has any restrictions on the sending frequency.

  2. 'django': Use the console processor to output information. You can use this processor during development (What? Print? Too low!)

  3. See comments for the last processor.

Finally, don’t forget to give the log path response permissions. For example, for the Apache2 server, you need to give www-data write permission:

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

For more detailed information on the configuration of Django log module logging, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template