The following is an example of Django using logging to print logs. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
Django uses python’s own logging as a log printing tool. Let’s briefly introduce logging.
logging is thread-safe, and it mainly consists of 4 parts:
Logger
The direct interface used by users, Pass the log to Handler
Handler
Control where the log is output, console, file...
A logger can have Multiple Handler
Filter
Control which logs can flow from the logger to the Handler
##Formatter
Control the format of the logUsers use logging.getLogger([name]) to obtain the logger instance. If there is no name, return the root logger (root logger) in the logger hierarchy. Calling this function with the same name always returns the same logger instance. This means that logger instances do not need to be passed around between various parts of the application. Django customizes log output by using LOGGING in the settings file (including defining logger, handler, formatter, etc.)For example, the settings file is defined as follows:
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[%(asctime)s] [%(levelname)s] %(message)s' }, }, 'handlers': { 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'verbose' }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'D:/monitor.log', 'formatter': 'verbose' }, 'email': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html' : True, } }, 'loggers': { 'django': { 'handlers': ['console', 'file', 'email'], 'level': 'INFO', 'propagate': True, }, }, }
Print log in code:
logger = logging.getLogger(‘django') logger.info(“This is an error msg”)
[2017-07-15 17:44:51,316] [ERROR] This is an error msg
In this way, the log is printed to the terminal and file.If you want to know more about django logging, please refer to the official website
https://docs.djangoproject.com/en/1.11/topics/logging/Related recommendations:
How Django loads css and js files and static images
The above is the detailed content of Django uses logging to print logs. For more information, please follow other related articles on the PHP Chinese website!