標籤:inter val bytes style 技術 src div erro port
1.列出所有狀態並列印到終端。
import logginglogging.debug("test debug")#調試,除錯logging.info("test")#資訊logging.warning("user [xsk] 3")#警告logging.error("test error")#錯誤logging.critical("server is down") #嚴重
註:嚴重的警告直接列印到終端,重上往下的優先順序。
2.將日誌列印到檔案內。
import logginglogging.basicConfig(filename=‘example.log‘,level=logging.INFO)
註:自動建立log檔案,並將資料自動列印到檔案內。
註:logging.basicConfig():建立記錄檔。
註:filename=:輸入記錄檔名。
註:level=:輸入警示層級。
註:輸入時,優先順序高的將不會輸出低優先順序的 警示資訊。
3.記錄日誌時,加入時間。
import logginglogging.basicConfig(filename=‘example.log‘,level=logging.INFO,format=‘%(asctime)s %(message)s‘,datefmt=‘%m/%d/%Y %I:%M:%S %p‘)
註:添加了時間的日誌格式變數,可自訂運行格式。
註:format=‘’:用來添加記錄日誌格式的模組參數。
註:datefmt=‘’:時間參數。
4、使日誌,定義成 終端檔案都可以輸出。
import logginglogger = logging.getLogger(‘TEST-LOG‘)#自訂名字logger.setLevel(logging.DEBUG)#設定最低等級ch = logging.StreamHandler()#終端輸出日誌ch.setLevel(logging.WARNING)#最小有限級fh = logging.FileHandler("access.log",encoding="utf-8")#檔案內的日誌fh.setLevel(logging.ERROR)#最小有限級fh_formatter = logging.Formatter(‘%(asctime)s %(filename)s:%(lineno)d %(module)s - %(levelname)s %(message)s‘)#fh日誌格式ch_formatter = logging.Formatter(‘%(asctime)s %(filename)s:%(lineno)d %(module)s - %(levelname)s %(message)s‘)#ch日誌格式fh.setFormatter(fh.formatter)#綁定fh handlerch.setFormatter(ch_formatter)#綁定ch handlerlogger.addHandler(fh)#logger 綁定fh handlerlogger.addHandler(ch)#logger 綁定ch handlerlogger.warning("ddd")#輸出logger.error("error happend..")#輸出v
註:將logger,handler,與formatter綁定。
5.定義日誌自訂 刪除。
(1)按檔案大小進行,刪除。
import loggingfrom logging import handlerslogger = logging.getLogger(‘TEST‘)log_file = "timelog.log"fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3,encoding="utf-8")formatter = logging.Formatter(‘%(asctime)s %(filename)s:%(lineno)d %(module)s - %(levelname)s %(message)s‘)fh.setFormatter(formatter)logger.addHandler(fh)logger.warning("test1")logger.warning("test2")logger.warning("test3")
註:需要使用handlers模組
註:handlers.RotatingFileHandler():來進行定義。
filename=:檔案名稱
maxBytes=:定義最大值
backupCount=:定義最多備份的檔案數
encodoing=:定義字元編碼。
(2)按時間進行,刪除。
import loggingfrom logging import handlerslogger = logging.getLogger(‘TEST‘)log_file = "timelog.log"fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)formatter = logging.Formatter(‘%(asctime)s %(filename)s:%(lineno)d %(module)s - %(levelname)s %(message)s‘)fh.setFormatter(formatter)logger.addHandler(fh)import timelogger.warning("test1")time.sleep(2)logger.warning("test2")time.sleep(2)logger.warning("test3")time.sleep(2)logger.warning("test4")
註:實現了,每5秒鐘備份一個日誌
註:handlers.TimedRotatingFileHandler():實現時間備份刪除。
wen=:選擇時間型別參數。
interval=:選擇對應參數的數量。
backupCount=:定義最多備份的檔案數
encodoing=:定義字元編碼
Python logging模組