標籤:ide att err 多個 寫日誌 設定 and 完成 gif
logging
用於便捷記錄日誌且安全執行緒的模組
import logging logging.basicConfig(filename=‘log.log‘, format=‘%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s‘, datefmt=‘%Y-%m-%d %H:%M:%S %p‘, level=10) logging.debug(‘debug‘)logging.info(‘info‘)logging.warning(‘warning‘)logging.error(‘error‘)logging.critical(‘critical‘)logging.log(10,‘log‘)
日誌等級:
CRITICAL = 50FATAL = CRITICALERROR = 40WARNING = 30WARN = WARNINGINFO = 20DEBUG = 10NOTSET = 0
註:只有【當前寫等級】大於【日誌等級】時,記錄檔才被記錄。
2、多檔案日誌
對於上述記錄日誌的功能,只能將日誌記錄在單檔案中,如果想要設定多個記錄檔,logging.basicConfig將無法完成,需要自訂檔案和日誌操作對象。
# 定義檔案file_1_1 = logging.FileHandler(‘l1_1.log‘, ‘a‘, encoding=‘utf-8‘)fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")file_1_1.setFormatter(fmt)file_1_2 = logging.FileHandler(‘l1_2.log‘, ‘a‘, encoding=‘utf-8‘)fmt = logging.Formatter()file_1_2.setFormatter(fmt)# 定義日誌logger1 = logging.Logger(‘s1‘, level=logging.ERROR)logger1.addHandler(file_1_1)logger1.addHandler(file_1_2)# 寫日誌logger1.critical(‘1111‘)
日誌一
# 定義檔案file_2_1 = logging.FileHandler(‘l2_1.log‘, ‘a‘)fmt = logging.Formatter()file_2_1.setFormatter(fmt)# 定義日誌logger2 = logging.Logger(‘s2‘, level=logging.INFO)logger2.addHandler(file_2_1)
日誌(二)
如上述建立的兩個日誌對象
- 當使用【logger1】寫日誌時,會將相應的內容寫入 l1_1.log 和 l1_2.log 檔案中
- 當使用【logger2】寫日誌時,會將相應的內容寫入 l2_1.log 檔案中
python之logging模組