python3:logging模塊 輸出日志到文件


python自動化測試腳本運行后,想要將日志保存到某個特定文件,使用python的logging模塊實現

參考代碼:

import logging

def initLogging(logFilename,e):

  logging.basicConfig(
                    level = logging.INFO,
                    format ='%(asctime)s-%(levelname)s-%(message)s',
                    datefmt = '%y-%m-%d %H:%M',
                    filename = logFilename,
                    filemode = 'a')
  
  filehandler = logging.FileHandler(logFilename,encoding='utf-8')
  logging.getLogger().addHandler(filehandler )
  log = logging.exception(e)
  return log

1.日志級別使用場景:
在終端輸出程序或腳本的使用方法:print
報告一個事件的發生(例如狀態的修改):logging.info()或logging.debug()
發生了一個特定的警告性的事件:logging.warn()
發生了一個特定的錯誤性的事件:raise
發生了一個特定的錯誤性的事件,但是又不想因為此錯誤導致程序退出(例如程序是一個守護進程):logging.error(),logging.exception(),logging.critical()

 

2.logging.basicConfig()函數中可通過具體參數來更改logging模塊默認行為,可用參數有:
level:設置日志級別
format:指定handler使用的日志顯示格式
datefmt:指定日期時間格式,如果format參數中存在asctime,則需要指定時間格式
filename:用指定的文件名創建FiledHandler,這樣日志會被存儲在指定的文件中
filemode:文件打開方式,在指定了filename時使用這個參數,默認值為“a”還可指定為“w”

 

3.format參數中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 數字形式的日志級別
%(levelname)s 文本形式的日志級別
%(pathname)s 調用日志輸出函數的模塊的完整路徑名,可能沒有
%(filename)s 調用日志輸出函數的模塊的文件名
%(module)s 調用日志輸出函數的模塊名
%(funcName)s 調用日志輸出函數的函數名
%(lineno)d 調用日志輸出函數的語句所在的代碼行
%(created)f 當前時間,用UNIX標准的表示時間的浮 點數表示
%(relativeCreated)d 輸出日志信息時的,自Logger創建以 來的毫秒數
%(asctime)s 字符串形式的當前時間。默認格式是 “2003-07-08 16:49:45,896”。逗號后面的是毫秒
%(thread)d 線程ID。可能沒有
%(threadName)s 線程名。可能沒有
%(process)d 進程ID。可能沒有
%(message)s用戶輸出的消息

 

4.logging模塊的了解,必須知道:Logger,Handler,Formatter,Filter
(1)logger 提供了應用程序可以直接使用的接口
每個程序在輸出信息之前都要獲得一個Logger
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或刪除指定的handler

(2)handler 將(logger創建的)日志記錄發送到合適的目的輸出
logging.FileHandler用於向一個文件輸出日志信息,不過FileHandler會幫你打開這個文件。它的構造函數是:
FileHandler(filename[,mode])filename是文件名,必須指定一個文件名;mode是文件的打開方式

(3)filter 提供了細度設備來決定輸出哪條日志記錄

(4)formatter 決定日志記錄的最終輸出格式

 

5.輸出日志結果:

18-06-12 17:34-ERROR-string indices must be integers
Traceback (most recent call last):
  File "C:/Users/xx/Documents/GitHub/python3/main/run_test.py", line 70, in go_on_run
    op_header.write_cookie()
  File "C:\Users\xx\Documents\GitHub\python3\util\operation_header.py", line 30, in write_cookie
    cookie = requests.utils.dict_from_cookiejar(self.get_cookie())
  File "C:\Users\xx\Documents\GitHub\python3\util\operation_header.py", line 25, in get_cookie
    url = self.get_response_url()+"&callback=jQuery21008240514814031887_1508666806688&_=1508666806689"
  File "C:\Users\xx\Documents\GitHub\python3\util\operation_header.py", line 18, in get_response_url
    url = self.response['data']['url'][0]
TypeError: string indices must be integers

參考文檔:

https://www.cnblogs.com/Xjng/p/8a481db3399827ecbdec888989f7c0d5.html

https://www.cnblogs.com/wenwei-blog/p/7196658.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM