日誌

1、basicConfig

  • 導入logging模塊
  • 簡單配置一下logging
  • 出現異常的時候(except),向日志裏寫錯誤信息
import logging
import traceback


logging.basicConfig(filename="x1.log",
                    format="%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s",
                    datefmt="%Y-%m-%d %H:%M:%S", level=30)
try:
    print(1/0)
except Exception:
    logging.error(traceback.format_exc())
    print("出現錯誤")
  • filename:文件名
  • format:數據的格式化輸出,最終在日誌文件中的樣子。時間-名稱-級別-模塊:錯誤信息
  • datefmt:時間的格式
  • level:錯誤的級別權重,當錯誤的級別權重大於等於leval的時候纔會寫入文件

CRITICAL = 50spa

FATAL = CRITICAL日誌

ERROR = 40code

WARNING = 30orm

WARN = WARNINGblog

INFO = 20io

DEBUG = 10form

LOG = 0class

2、FileHandler

  • 可實現日誌分開記錄

 

import logging
import traceback

file_handler = logging.FileHandler("x2.log", "a", encoding='UTF-8')
file_handler.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s"))

logger1 = logging.Logger("系統A", level=30)
logger1.addHandler(file_handler)

logger1.error("出現錯誤")


file_handler = logging.FileHandler("x3.log", "a", encoding='UTF-8')
file_handler.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s"))

logger2 = logging.Logger("系統B", level=30)
logger2.addHandler(file_handler)

try:
    print(1/0)
except Exception:
    logger2.error(traceback.format_exc())
    print("出錯了")
相關文章
相關標籤/搜索