Django logging configuration and use details
- 2021-07-26 07:57:43
- OfStack
1. settings. py file
The following is the logging configuration commonly used in writing Django projects in my work.
# Log configuration
BASE_LOG_DIR = os.path.join(BASE_DIR, "log")
LOGGING = {
'version': 1, # Reserved word
'disable_existing_loggers': False, # Disable log instances that already exist
'formatters': { # Define the format of the log
'standard': {
'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
'[%(levelname)s][%(message)s]'
},
'simple': {
'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
},
'collect': {
'format': '%(message)s'
}
},
'filters': { # Define filters for logs
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': { # Log handler
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'], # Only when Django debug For True Print the log on the screen when
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'SF': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # Save to file, automatically cut according to file size
'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"), # Log file
'maxBytes': 1024 * 1024 * 500, # Log size 50M (It is best not to exceed 1G )
'backupCount': 3, # The number of backups is 3 xx.log --> xx.log.1 --> xx.log.2 --> xx.log.3
'formatter': 'standard',
'encoding': 'utf-8', # Encoding format of file records
},
'TF': {
'level': 'INFO',
'class': 'logging.handlers.TimedRotatingFileHandler', # Save to file and cut automatically according to time
'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"), # Log file
'backupCount': 3, # The number of backups is 3 xx.log --> xx.log.2018-08-23_00-00-00 --> xx.log.2018-08-24_00-00-00 --> ...
'when': 'D', # Every day 1 Cut, Optional values are S/ Seconds M/ Points H/ Hours D/ Days W0-W6/ Week (0= Week 1) midnight/ If no time is specified, it defaults to midnight
'formatter': 'standard',
'encoding': 'utf-8',
},
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler', # Save to file, automatically cut
'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"), # Log file
'maxBytes': 1024 * 1024 * 5, # Log size 50M
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8',
},
'collect': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # Save to file, automatically cut
'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
'maxBytes': 1024 * 1024 * 50, # Log size 50M
'backupCount': 5,
'formatter': 'collect',
'encoding': "utf-8"
}
},
'loggers': { # Log instance
'': { # Default logger Apply the following configuration
'handlers': ['SF', 'console', 'error'], # After going online, you can put 'console' Remove
'level': 'DEBUG',
'propagate': True, # Upward or not 1 Grade logger Instance delivers log information
},
'collect': { # Called 'collect' Adj. logger It is also handled separately
'handlers': ['console', 'collect'],
'level': 'INFO',
}
},
}
2. Create an log folder under the Django root
3. Use of logging
With logging configuration, we will try not to use print statements to print information and debug BUG in future projects. More professionally, we will use logger objects to save and print error messages.
For example:
import logging
# Instantiation logging Object , With the name of the current file as the logger Name of the instance
logger = logging.getLogger(__name__)
# Generate 1 A name is called collect Log instance of
logger_c = logging.getLogger('collect')
class Foo(object):
def test(self, data):
logger.debug(data) # Print data
try:
...
except Exception as e:
logger.error(str(e)) # Save and print error messages