1. 程式人生 > >Python 配置日誌檔案

Python 配置日誌檔案

在程式開發階段,顯然我們需要大量的日誌。打個比方,我們的程式是一個賣東西的網站,那麼關於使用者關於錢的,關於商品銷售等所有操作我們都應該記錄下來,起碼可以知道使用者花了多少錢,商品銷售的怎麼樣了。

當我們使用爬蟲爬取網頁時,我們通過日誌,能更直觀得了解到我們得爬蟲爬到哪了,資料是怎樣的,有沒有哪裡報錯等等等等資訊。

日誌級別:
critical > error > warning > info > debug
級別越高列印的日誌越少,反之亦然,
debug : 列印全部的日誌
info : 列印info,warning,error,critical級別的日誌
warning : 列印warning,error,critical級別的日誌
error : 列印error,critical級別的日誌
critical : 列印critical級別

好了,不扯蛋了,咱們開始配置日誌檔案吧:

import logging   
import getpass  
import sys
class MyLog(object):
    def __init__(self):
        self.user=getpass.getuser()   #獲取系統當前登陸使用者(即系統操作使用者)
        self.logger=logging.getLogger(self.user)  #日誌物件
        self.logger.setLevel(logging.DEBUG)   #預設日誌等級為debug級
        
     '''定義日誌檔名
	sys.argv是程式執行該py檔案時的路徑,後面我有截圖
	所以這裡我把路徑的字尾名改成.log,其他不變,得到跟程式檔案同名的日誌檔案   
	當然,你也可以設定一個自己想存放的路徑,這個沒有影響的
	好比如我想把輸出的日誌檔案放到我的桌面上,則改成:
	self.logFile=r'C:\Users\Computer-huangbiao\Desktop\MyLog.log'就可以了
     '''
        self.testLogFile=sys.argv    #這裡用來做測試,後面有截圖顯示
        self.logFile=sys.argv[0][0:-3]+'.log'
        print('self.testLogFile:',self.testLogFile)
        print('self.logFile:',self.logFile)
	#關於日誌的格式引數設定,大家可以參考:(https://blog.csdn.net/enjoy_endless/article/details/76214583)
        self.formatter=logging.Formatter( '%(asctime)-12s %(levelname)-8s %(name)-10s %(message)-12s\r\n' )

###     日誌輸入到日誌檔案內
        self.logHand = logging.FileHandler( self.logFile , encoding='utf8' )
        self.logHand.setFormatter( self.formatter )
        self.logHand.setLevel( logging.DEBUG )
        
        #二進位制流輸出到Console,這裡也可以不配置,也就時不在Console上顯示
        self.logHandSt = logging.StreamHandler()
        self.logHandSt.setFormatter( self.formatter )
        self.logHandSt.setLevel(logging.DEBUG)
        
        #把Hand加入到logger物件中
        self.logger.addHandler( self.logHand )
        self.logger.addHandler( self.logHandSt )

###   日誌的五個級別對應下面五個函式 , 自上而下級別原來越高
    def debug(self,msg):
        self.logger.debug( msg )
        
    def info(self,msg):
        self.logger.info( msg )
        
    def warn(self,msg):
        self.logger.debug( msg )
        
    def error(self,msg):
        self.logger.debug( msg )
    
    #臨界的,批評的
    def critical(self,msg):
        self.logger.critical( msg )
        
if __name__=='__main__':
    mylog=MyLog()
    mylog.debug('I am debug 測試中文')
    mylog.info('I am info ')
    mylog.warn('I am warn ')
    mylog.error('I am error ')
    mylog.critical('I am critical 測試中文')


關於上面提到的 sys.argv的意思如下
在這裡插入圖片描述

Console面板截圖:

在這裡插入圖片描述

MyLog.log截圖:

在這裡插入圖片描述

當我們寫好這個模組後,以後想要在其他的python程式中使用debug的話,可以直接 from MyLog import MyLog 匯入哦
感謝您的閱讀!