Django log — output to log file

Time:2020-6-4

We all know that it is very important to log in the project, because bugs appear when the project is running in the server and there is no log to record. We may not know that bugs exist at all. In the past, I didn’t feel that I had made my own development in school. Now I think that diary is really indispensable.

First understand the five levels of logging:

  1. Debug: low level system information for debugging purposes
  2. Info: general system information list content
  3. Warning: describe the small problems that have occurred
  4. Error: describe the main problems that have occurred
  5. Critical: describe serious problems that have occurred

Step 1: configure the setting.py file

LOGGING = {
    'version': 1,
    'disable_ existing_ Loggers': false if debug else true, ා disable existing loggers or not
    'formatters': {ා format of log information display
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)s %(message)s'
            # "class": "pythonjsonlogger.jsonlogger.JsonFormatter"
        },
        'simple': {
            'format': '%(levelname)s %(asctime)s %(module)s %(funcName)s %(lineno)d %(message)s'
            # "class": "pythonjsonlogger.jsonlogger.JsonFormatter"
        }, logging level + time date + module name + function name + line number + logging message
    },
    'filters': {filter logs
        'require_ debug_ True ': {Django only outputs logs in debug mode
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {log processing method
        'console': {output log to terminal
            'level': 'DEBUG' if DEBUG else 'INFO',
            'filters': ['require_ debug_ True '], ා debug is true before output
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        },
        'info': {ා output log to file
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename':  os.path.join (BASE_ DIR+'/logs/', " info.log "), the location of the log file
            'maxbytes': 300 * 1024 * 1024, X 300m size
            'backupCount': 10,
            'formatter': 'verbose',
            'encoding': 'utf-8'
        },
        'demo': {ා specifically define a log to collect specific information
            'level': 'INFO',
            'class': ' logging.handlers.RotatingFileHandler , save to file, auto cut
            'filename': os.path.join(BASE_DIR+'/logs/', "demo.log"),
            'maxbytes': 1024 * 1024 * 50, ා log size 50m
            'backupCount': 5,
            'formatter': 'verbose',
            'encoding': "utf-8"
        },
        'city': {ා specifically define a log to collect specific information
            'level': 'INFO',
            'class': ' logging.handlers.RotatingFileHandler , save to file, auto cut
            'filename': os.path.join(BASE_DIR+'/logs/', "city.log"),
            'maxbytes': 1024 * 1024 * 50, ා log size 50m
            'backupCount': 5,
            'formatter': 'verbose',
            'encoding': "utf-8"
        },

    },
    'loggers': {loggers
        "Django": {ා the default logger is configured as follows
            "handlers": ["info", "console"],
            "propagate": True,
            "level": "INFO"
        },
        'demo_ Log ': {ා the logger named' demo 'is also handled separately
            'handlers': ['demo'],
            "propagate": True,
            'level': 'INFO',
        },
        'city_ Log ': {ා the logger named' city 'is also handled separately
            'handlers': ['city'],
            "propagate": True,
            'level': 'INFO',
        },
    }
    }

formatters:Various formats can be defined for the display of log information, including ‘verbose’ and ‘simple’
For example, the format of ‘verbose’ is’%(levelname)s %(asctime)s %(module)s %(lineno)s %(message)s
The example of log file printing is as follows:Info 2019-12-05 09:04:28707 views 234 printed out!!!
handlers:Log processing methods can be defined in many ways. Generally, I am used to adding one Django sub application every time I add one. The ‘demo’ and ‘city’ above are sub applications.
loggers:Loggers, I used to write one-to-one correspondence with handlers.
Both handlers and loggers have levels, which are different:
1. The level in loggers indicates the acceptable error level, that is to say, loggers accept errors of level or higher than level, which is determined by propagate: if propagate is true, propagate upward;
2. The level of handlers indicates the log level
Note:To create a new logs directory in the root directory of the project to store log files, the log files do not need to be created manually, but will be created by themselves when the project is running.

Step 2: add exceptions.py File encapsulation log

import logging
logger = logging.getLogger('django')
logger_demo = logging.getLogger('demo_log')
logger_city = logging.getLogger('city_log')

Step 3: print the log

logger.info ("I print on the console as well as on the info.log Up ")
logger.error ("I print on the console as well as on the info.log Up ")
logger_ demo.info ("I print on demo.log Up ")
logger_ demo.error ("I print on demo.log Up ")
logger_ city.info ("I print on city.log Up ")
logger_ city.error ("I print on city.log Up ")

This is done, is it very simple and easy!!!