Python 學習之路 Logging

2022-09-08 18:45:13 字數 2655 閱讀 6674

logging.debug('

every step log')

logging.info(

"history")

logging.warn(

"prompt something

")

輸出:warning:root:prompt something

日誌預設輸出到螢幕,並且只輸出warning(包括warning)以上級別的log。日誌級別從小到大: notest

1

#把日誌記錄到檔案,可以加很多引數,level 只記錄某個級別以上的log,%i 12小時 %h 23小時,%p上午,下午,%a星期幾

2 logging.basicconfig(filename='

example.log

',level=logging.info,

3 format='

%(asctime)s %(message)s

',datefmt='

%m%d%y %i:%m:%s %p')

45#在螢幕輸出log以及log對應的級別,以下的log級別從低到高

6 logging.debug('

every step log

')#debug時才輸出

7 logging.info("

history

")#正常執行時輸出的記錄

8 logging.warn("

prompt something")

9 logging.error("

something error")

10 logging.critical("

it's very critical

")

logging.basicconfig函式各引數:

filename: 指定日誌檔名

filemode: 和file函式意義相同,指定日誌檔案的開啟模式,'w'或'a'

format: 指定輸出的格式和內容,format可以輸出很多有用資訊,如上例所示:

%(levelno)s: 列印日誌級別的數值

%(levelname)s: 列印日誌級別名稱

%(pathname)s: 列印當前執行程式的路徑,其實就是sys.ar**[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

stream: 指定將日誌的輸出流,可以指定輸出到sys.stderr,sys.stdout或者檔案,預設輸出到sys.stderr,當stream和filename同時指定時,stream被忽略

1

#把log同時列印在螢幕和檔案

2import

logging34

#create logger

5 logger = logging.getlogger('

test-log

') #

get the logger object first

6 logger.setlevel(logging.debug)#

set globel level

78 ch = logging.streamhandler()#

print the log on monitor

9ch.setlevel(logging.debug)

1011 fh = logging.filehandler("

access.log")

12fh.setlevel(logging.warning)

1314 formatter = logging.formatter('

%(asctime)s - %(name)s - %(levelname)s - %(message)s')

15 formatter_file = logging.formatter('

%(asctime)s - %(levelname)s - %(message)s')

1617

ch.setformatter(formatter)

18fh.setformatter(formatter_file)

1920

logger.addhandler(ch)

21logger.addhandler(fh)

2223 logger.debug('

debug message')

24 logger.info('

info message')

25 logger.warn('

warn message')

26 logger.error('

error message')

27 logger.critical('

critical message

')

Python學習之路

python 十分鐘入門 python 菜鳥教程 pycharm安裝numpy python 檔案讀取 with open xml path,r as fr content fr.read python讀取檔案時提示 unicodedecodeerror gbk codec can t decode...

python學習之路

簡單理解下,yield可以先看作 return 直接返回某個值,返回之後程式就不再往下執行了。看做return之後再把它看做乙個是生成器 generator 的一部分 帶yield的函式才是真正的迭代器 def foo print starting.while true res yield 4pri...

python學習之路

1 讀純文字檔案 file open file.close 做好前置準備,以及首尾語句 1 file open chinese.txt mode r encoding utf 8 content file read print content file close 2 寫純文字檔案 引數mode r...