python之logging模組

來源:互聯網
上載者:User

標籤: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模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.