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, request information, setting configuration, trackback information, all are available, enough for usDebuggingis over. However, in an online environment, it is verysafe(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 module ofPythonand 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
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!')
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 it to a file, database, or send an email).
Generally speaking, the handler can be send_email, error_file and other 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, }, } }
In the aboveconfiguration file, there are three log processors. They are:
'django.request': Django request errors will be automatically recorded, and then use debug to record the information to the file, and mail_admins will send the information throughmailTo the administrator. 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.
'django': Use the console processor to output information. You can use this processor during development (What? Print? Too low!)
Seecommentfor the last processor.
Finally, don’t forget to give the log path response permissions. For example, for Apache2 server, you need to give www-data write permission:
sudo chown -R [yourname]:www-data [log] sudo chmod -R g+s [log]
Summary
[Related recommendations]
1.Python is free Video tutorial
2.Python meets data collection video tutorial
The above is the detailed content of Detailed explanation of the configuration of Django log module. For more information, please follow other related articles on the PHP Chinese website!