天天看點

python logging子產品

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/12/8 0008 14:30
# @Author  : ming

import logging

logging.basicConfig(level=logging.WARNING,  # 大于等于warning級别的才會被記錄
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='myapp.log',
                    filemode='w', )

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('This is error message')
logging.critical("This is critical message")
logging.log(logging.ERROR, 'This is error message')  # 也可以自己寫到日志級别      
logging.basicConfig函數各參數:
filename: 指定日志檔案名
filemode: 和file函數意義相同,指定日志檔案的打開模式,'w'或'a'
format: 指定輸出的格式和内容,format可以輸出很多有用資訊,如上例所示:
 %(levelno)s: 列印日志級别的數值
 %(levelname)s: 列印日志級别名稱
 %(pathname)s: 列印目前執行程式的路徑,其實就是sys.argv[0]
 %(filename)s: 列印目前執行程式名
 %(funcName)s: 列印日志的目前函數
 %(lineno)d: 列印日志的目前行号
 %(asctime)s: 列印日志的時間
 %(thread)d: 列印線程ID
 %(threadName)s: 列印線程名稱
 %(process)d: 列印程序ID
 %(message)s: 列印日志資訊
datefmt: 指定時間格式,同time.strftime()
level: 設定日志級别,預設為logging.WARNING
日志級别大小關系為:CRITICAL(50) > ERROR(40) > WARNING(30) > INFO(20) > DEBUG(10) > NOTSET(0),當然也可以自己定義日志級别。
stream: 指定将日志的輸出流,可以指定輸出到sys.stderr,sys.stdout或者檔案,預設輸出到sys.stderr,當stream和filename同時指定時,stream被忽略      
運作結果
Tue, 12 Dec 2017 14:08:45 l1.py[line:16] WARNING This is warning message
Tue, 12 Dec 2017 14:08:45 l1.py[line:17] ERROR This is error message
Tue, 12 Dec 2017 14:08:45 l1.py[line:18] CRITICAL This is critical message
Tue, 12 Dec 2017 14:08:45 l1.py[line:19] ERROR This is error message      

作者:楊永明

出處:https://www.cnblogs.com/ming5218/

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接。

下一篇: 每日一練