【Python-django后端開發】logging日制配置詳解!!!


 

官方文檔請查看:https://docs.djangoproject.com/en/1.11/topics/logging/

 

 

1. 配置工程日志,在setting.py里,如下

 

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,  # 是否禁用已經存在的日志器
    'formatters': {  # 日志信息顯示的格式
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
        },
    },
    'filters': {  # 對日志進行過濾
        'require_debug_true': {  # django在debug模式下才輸出日志
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {  # 日志處理方法
        'console': {  # 向終端中輸出日志
            'level': 'INFO',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {  # 向文件中輸出日志
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs/liuxinyu.log'),  # 日志文件的位置
            'maxBytes': 300 * 1024 * 1024,
            'backupCount': 10,
            'formatter': 'verbose'
        },
    },
    'loggers': {  # 日志器
        'django': {  # 定義了一個名為django的日志器
            'handlers': ['console', 'file'],  # 可以同時向終端與文件中輸出日志
            'propagate': True,  # 是否繼續傳遞日志信息
            'level': 'INFO',  # 日志器接收的最低日志級別
        },
    }
}

  

2. 准備日志文件目錄,在工程文件下創建logs文件夾,在logs文件夾里創建liuxinyu.log文件(根據上面的配置來的)

 

 

 

 

 

3. 日志記錄器的使用

不同的應用程序所定義的日志等級可能會有所差別,分的詳細點的會包含以下幾個等級:

  • FATAL/CRITICAL = 重大的,危險的
  • ERROR = 錯誤
  • WARNING = 警告
  • INFO = 信息
  • DEBUG = 調試
  • NOTSET = 沒有設置
import logging

# 創建日志記錄器
logger = logging.getLogger('django')
# 輸出日志
logger.debug('測試logging模塊debug')
logger.info('測試logging模塊info')
logger.error('測試logging模塊error')

  

4. 取消Git記錄工程日志

 

 

  • 建立代碼倉庫時,生成的忽略文件中已經默認忽略掉了*.log。

 

  • logs文件目錄需求被Git倉庫記錄和管理。
  • 當把*.log都忽略掉后,logs文件目錄為空。
  • 但是,Git是不允許提交一個空的目錄到版本庫上的。

 

解決:

 

  • 在空文件目錄中建立一個.gitkeep文件,然后即可提交。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM