說明 | |
---|---|
DEBUG | 輸出詳細的運行情況,主要用於調試。 |
INFO | 確認一切按預期運行,一般用於輸出重要運行情況。 |
WARNING | 系統運行時出現未知的事情(如:警告內存空間不足),但是軟件還可以繼續運行,可能以后運行時會出現問題。 |
ERROR | 系統運行時發生了錯誤,但是還可以繼續運行。 |
CRITICAL | 一個嚴重的錯誤,表明程序本身可能無法繼續運行。 |
這5個等級,也分別對應5種打印日志的方法:debug、info、warning、error、critical。默認的日志收集器是收集WARNING以上等級的日志。
2、日志文件分類存儲代碼,創建文件login_demo02.py
import logging class log: def __init__(self): # 創建自己的日志收集器 self.my_log = logging.getLogger("my_log") # 設置收集的日志等級,設置為DEBUG等級 self.my_log.setLevel("DEBUG") # 日志輸出渠道 # 創建一個日志輸出渠道(輸出到控制台),並且設置輸出的日志等級為INFO以上 self.l_s = logging.StreamHandler() self.l_s.setLevel("DEBUG") # 創構建一個日志輸出渠道(輸出到文件) l_f = logging.FileHandler("error.log",encoding='utf8') l_f.setLevel("ERROR")#設置輸出的日志等級為ERROR以上 l_d=logging.FileHandler("debug.log",encoding='utf-8') l_d.setLevel("DEBUG")#設置輸出的日志等級為DEBUG以上 cc=logging.FileHandler("info.log",encoding='utf-8') cc.setLevel("INFO")#設置輸出的日志等級為INFO以上 #將日志輸出渠道添加到日志收集器中 self.my_log.addHandler(self.l_s) self.my_log.addHandler(l_f) self.my_log.addHandler(l_d) self.my_log.addHandler(cc) # 設置日志輸出的格式 # 可以通過logging.Formatter指定日志的輸出格式,這個參數可以輸出很多有用的信息,如下: # % (name)s: 收集器名稱 # % (levelno)s: 打印日志級別的數值 # % (levelname)s: 打印日志級別名稱 # % (pathname)s: 打印當前執行程序的路徑,其實就是sys.argv() # % (filename)s: 打印當前執行程序名 # % (funcName)s: 打印日志的當前函數 # % (lineno)d: 打印日志的當前行號 # % (asctime)s: 打印日志的時間 # % (thread) d: 打印線程ID # % (threadName)s: 打印線程名稱 # % (process) d: 打印進程ID # % (message) s: 打印日志信息 ft = "%(asctime)s - [%(filename)s -->line:%(lineno)d] - %(levelname)s: %(message)s"#工作中常用的日志格式 ft = logging.Formatter(ft) # 設置控制台和日志文件輸出日志的格式 self.l_s.setFormatter(ft) l_f.setFormatter(ft) l_d.setFormatter(ft) cc.setFormatter(ft)
if __name__ == '__main__': my_log=log().my_log ss="一條小日志" my_log.info(ss) my_log.debug(ss) my_log.error(ss)
運行結果如下:
3、其他文件調用
from login_demo02 import * my_log=log().my_log cc="這是一條日志" my_log.debug(cc) my_log.info(cc) my_log.error(cc)
運行結果:
使用日志配置進行日志保存:
創建log.conf文件,內容如下:
[loggers] keys=root,infoLogger [logger_root] level=DEBUG handlers=consoleHandler,fileHandler [logger_infoLogger] handlers=consoleHandler,fileHandler qualname=infoLogger propagate=0 [handlers] keys=consoleHandler,fileHandler [handler_consoleHandler] class=StreamHandler level=INFO formatter=form02 args=(sys.stdout,) [handler_fileHandler] class=FileHandler level=INFO formatter=form01 args=('../log/infolog/info.log', 'a') [formatters] keys=form01,form02 [formatter_form01] format=>%(asctime)s | %(levelname)s |%(filename)s.%(funcName)s-->line:%(lineno)d: %(message)s [formatter_form02] format=>%(asctime)s | %(levelname)s |%(filename)s.%(funcName)s-->line:%(lineno)d: %(message)s
代碼如下:
import logging from logging import config class MyLog(object): def __init__(self): config.fileConfig('../config/log.conf') self.logger = logging.getLogger() @property def my_logger(self): return self.logger if __name__ == '__main__': log = MyLog() log.my_logger.info('it is my test log message info')