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

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

參考代碼:python

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()cookie

 

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):增長或刪除指定的handlerurl

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

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

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

 

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

http://www.javashuo.com/article/p-rpnwosnj-dw.html

相關文章
相關標籤/搜索