python logging—模組

來源:互聯網
上載者:User

標籤:orm   .com   com   text   文本   注意   用法   case   針對   

python logging模組

python logging提供了標準的日誌介面,python logging日誌分為5個等級:

debug(), info(), warning(), error() and critical()

簡單用法
import logginglogging.warning("warning.........")logging.critical("server is down")

print:

WARNING:root:warning.........CRITICAL:root:server is down

5個記錄層級所代表的意思:

Level 說明
DEBUG Detailed information, typically of interest only when diagnosing problems.
INFO Confirmation that things are working as expected.
WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR Due to a more serious problem, the software has not been able to perform some function.
CRITICAL A serious error, indicating that the program itself may be unable to continue running.
把日誌寫到檔案裡
import logginglogging.basicConfig(filename="log_test.log", level=logging.INFO) #此處定義了記錄層級,INFO以及高於INFO的日誌會被記錄logging.debug("debug..............")logging.info("info..............")logging.warning("warning...........")

結果:

我們把記錄層級調整一下:

import logginglogging.basicConfig(filename="log_test.log", level=logging.DEBUG) #level 改為 debuglogging.debug("debug..............")logging.info("info..............")logging.warning("warning...........")

結果:

debug 層級的日誌已經記錄了。另外,日誌的寫入方式是追加,不會覆蓋之前的日誌。

自訂日誌格式

日誌格式參數:

%(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 使用者輸出的訊息

上斷代碼看一下:

import logginglogging.basicConfig(filename="log_test.log",                    level=logging.DEBUG,                    format="%(asctime)s - %(levelname)s - %(module)s - %(lineno)d %(message)s",                    datefmt="%Y-%m-%d %I:%M:%S:%p"                    )def fun1():    logging.error("error......")fun1()logging.debug("debug..............")logging.info("info..............")logging.warning("warning...........")

結果:

進階用法
 1.產生logger對象logger = logging.getLogger("web")logger.setLevel(logging.INFO) #設定記錄層級。預設記錄層級為 warning# 2.產生handler對象console_handler = logging.StreamHandler()  # 用於列印的handlerconsole_handler.setLevel(logging.WARNING) #也可以專門針對 handler設定記錄層級file_handler = logging.FileHandler("web.log")  # 用於輸出到檔案的 handlerfile_handler.setLevel(logging.ERROR)# 2.1 把handler 對象 綁定到 loggerlogger.addHandler(console_handler)logger.addHandler(file_handler)# 3.產生formatter 對象console_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")file_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(lineno)s - %(message)s")# 3.1 把formatter 對象 綁定到 handlerconsole_handler.setFormatter(console_formatter)file_handler.setFormatter(file_formatter)logger.info("info----")logger.warning("warning-------------")logger.error("error-------")

全域設定的記錄層級 和 handler等設定的記錄層級,是逐級過濾的。

比如:

  • 全域設定的層級是 info ,handler 設定的層級是 debug , 到最後,debug層級的日誌會被過濾掉
  • 全域設定的界別是 info,handler設定的層級是 error ,到最後,error已經高於error 層級的日誌會被輸出

過濾日誌:

# *_*coding:utf-8 *_*import loggingclass IngonreBackupLogFilter(logging.Filter):    """尋找帶 db backup 的日誌"""    def filter(self, record):#固定寫法        return "db backup" in record.getMessage()# 1.產生logger對象logger = logging.getLogger("web")logger.setLevel(logging.DEBUG) #設定記錄層級。預設記錄層級為 warning# 1.1 把filter對象添加到logger中logger.addFilter(IngonreBackupLogFilter())# 2.產生handler對象console_handler = logging.StreamHandler()  # 用於列印的handlerfile_handler = logging.FileHandler("web.log")  # 用於輸出到檔案的 handler# 2.1 把handler 對象 綁定到 loggerlogger.addHandler(console_handler)logger.addHandler(file_handler)# 3.產生formatter 對象console_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")file_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(lineno)s - %(message)s")# 3.1 把formatter 對象 綁定到 handlerconsole_handler.setFormatter(console_formatter)file_handler.setFormatter(file_formatter)logger.info("info----")logger.warning("warning-------------")logger.error("error-------")logger.error("error db backup ----")# 列印:# 2018-07-08 20:10:40,023 - web - ERROR - error db backup ----

檔案自動截斷:

import loggingfrom logging import handlerslogger = logging.getLogger(__name__)log_file = "timelog.log"# file_handler = handlers.RotatingFileHandler(filename=log_file, maxBytes=10, backupCount=3) file_handler = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)formatter = logging.Formatter('%(asctime)s - %(module)s - %(lineno)d - %(message)s')file_handler.setFormatter(formatter)logger.addHandler(file_handler)logger.warning("test1")logger.warning("test2")logger.warning("test3")logger.warning("test4")

結果:會按時間產生不同的記錄檔:

file_handler = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)

You can use the?when?to specify the type of?interval. The list of possible values is below. Note that they are not case sensitive.

(你可以使用when來指定interval的類型。可能的值列表如下。注意它們不是區分大小寫。 )

(這個英語還是有很有必要花時間去搞一下的)

Value Type of interval
‘S‘ Seconds
‘M‘ Minutes
‘H‘ Hours
‘D‘ Days
‘W‘ Week day (0=Monday)
‘midnight‘ Roll over at midnight 午夜roll over

python logging—模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.