LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
# LOGGING FORMAT
'standard': {
'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] '
'[%(levelname)s]- %(message)s'},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
# 過濾
'filters': {
},
# 定義具體處理日志的方式
'handlers': {
# 預設記錄所有日志
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(log_path, 'debug-{}.log'.format(time.strftime('%Y-%m-%d'))),
'maxBytes': 1024 * 1024 * 5, # 檔案大小
'backupCount': 5, # 備份數
'formatter': 'simple', # 輸出格式
'encoding': 'utf-8', # 設定預設編碼,否則列印出來漢字亂碼
},
# 輸出錯誤日志
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(log_path, 'error-{}.log'.format(time.strftime('%Y-%m-%d'))),
'maxBytes': 1024 * 1024 * 5, # 檔案大小
'backupCount': 5, # 備份數
'formatter': 'simple', # 輸出格式
'encoding': 'utf-8', # 設定預設編碼
},
# 控制台輸出
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
# 輸出info日志
'info': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(log_path, 'info-{}.log'.format(time.strftime('%Y-%m-%d'))),
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'simple',
'encoding': 'utf-8', # 設定預設編碼
},
},
# 配置用哪幾種 handlers 來處理日志
'loggers': {
# 類型 為 django 處理所有類型的日志, 預設調用
'django': {
'handlers': ['default', 'console'],
'level': 'INFO',
'propagate': False
},
# log 調用時需要當作參數傳入
'log': {
'handlers': ['error', 'info', 'console', 'default'],
'level': 'INFO',
'propagate': True
},
}
}
import time
cur_path = os.path.dirname(os.path.realpath(__file__)) # log_path是存放日志的路徑
log_path = os.path.join(os.path.dirname(cur_path), 'logs')
if not os.path.exists(log_path): os.mkdir(log_path) # 如果不存在這個logs檔案夾,就自動建立一個