1import
logging
2'''
#1、日誌列印
3#logging.warning("user [wohaoshuai] attempted wrong password more than 3 times")
4#logging.critical("server is down")56
#2、日誌記錄到檔案裡
7#如果想把日誌寫到檔案裡,也很簡單
8logging.basicconfig(filename="wohaoshuai.log",level=logging.info,format="%(asctime)s %(message)s",datefmt="%y-%m-%d %h:%m:%s")
9#其實asctime就是日誌生成時間,message就是訊息
1011
#level級別一共有以下幾個:debug(若級別為debug,則不會存到檔案中),info,warning,error,critical
12logging.debug("this message should go to the log file")
13logging.info("so should this")
14logging.warning("and this,too")
15#其中下面這句中的level=loggin.info意思是,把日誌記錄級別設定為info
16'''17#
3、要把日誌既生成到螢幕又記錄到檔案
1819
#create logger 建立一個logging物件
20 logger = logging.getlogger("
test-log")
21 logger.setlevel(logging.debug)#
相當於設定全域性的level為debug,全域性的優先順序最高
222324#
create console handler and set level to debug 建立一個負責螢幕輸出的handler
25 ch =logging.streamhandler()
26ch.setlevel(logging.debug)
2728
#create file handler and set level to warning #建立一個檔案handler
29 fh = logging.filehandler("
access.log")
30 fh.setlevel(logging.info)#
設定為info則info以下級別全部列印到檔案中
3132
#create formatter 建立格式
33 formatter = logging.formatter("
%(asctime)s - %(name)s - %(levelname)s - %(message)s")
3435
#add formatter to ch and fh 把格式物件賦給螢幕和檔案
36ch.setformatter(formatter)
37fh.setformatter(formatter)
3839
#add ch and fh to logger
40logger.addhandler(ch)
41logger.addhandler(fh)
4243
#44 logger.debug("
debug message")
45 logger.info("
info message")
46 logger.warn("
warn message")
47 logger.error("
error message")
48 logger.critical("
critical message
")
知識點3中螢幕列印為:

access.log檔案中為:
2018-09-11 21:55:26,294 - test-log - info - info message2018-09-11 21:55:26,294 - test-log - warning - warn message
2018-09-11 21:55:26,294 - test-log - error - error message
2018-09-11 21:55:26,294 - test-log - critical - critical message
python logging
作用 報告狀態 錯誤和資訊訊息。 logging模組定義了一個標準api,用來報告應用和庫的錯誤及狀態資訊。由一個標準庫模組提供日誌api的...
python logging模組
1 簡介 記錄日誌 2 級別 1 logging debug debug information 2 logging info normal...
python模組 logging
1 import logging 23 logging debug debug message 4 logging info ingo me...