python中logging包的使用總結,pythonlogging

來源:互聯網
上載者:User

python中logging包的使用總結,pythonlogging

1.logging 簡介

Python的logging package提供了通用的日誌系統,可以方便第三方模組或者是應用使用。這個模組提供不同的記錄層級,並可以採用不同的方式記錄日誌,比如檔案,HTTP GET/POST,SMTP,Socket等,甚至可以自己實現具體的日誌記錄方式。

logging包中定義了Logger、Formatter、Handler和Filter等重要的類,除此之外還有config模組。

Logger是日誌對象,直接提供日誌記錄操作的介面

Formatter定義日誌的記錄格式及內容

Handler定義日誌寫入的目的地,你可以把日誌儲存成本地檔案,也可以每個小時寫一個記錄檔,還可以把日誌通過socket傳到別的機器上。python提供了十幾種實用handler,比較常用的有StreamHandler,BaseRotatingHandler,SocketHandler,DatagramHandler,SMTPHandler等。我們可以通過Logger對象的addHandler()方法,將log輸出到多個目的地。

2.Logging package

在python編程中,引入了Logging package,那麼可以存在一個名稱為root的Logging對象,以及很多其他名稱的Logging對象。不同的Logger對象的Handler,Formatter等是分開設定的。

(1)logging.getLogger() 如果getLogging中不帶參數,那麼返回的是名稱為root的Logger對象,如果帶參數,那麼就以該參數為名稱的Logger對象。同名稱的Logger對象是一樣的。

(2)logging.basicConfig() 此方法是為名稱為root的Logger對象進行配置。

(3)logging.info() logging.debug()等,使用的root Logger對象進行資訊輸出。如果是用其他的Logging對象進行log輸出,可以使用Logging.getLogger(name).info()來實現。

(4)日誌的等級

CRITICAL = 50 ERROR = 40 WARNING = 30 INFO = 20 DEBUG = 10 NOTSET = 0 

在python中有0,10,20,30,40,50這6個等級數值,這6個等級數值分別對應了一個字串常量,作為等級名稱,如上。但是可以通過logging.addLevelName(20, "NOTICE:")這個方法來改變這個映射關係,來定製化日誌等級名稱。

通過Logger對象的setLevel()方法,可以配置Logging對象的預設日誌等級,只有當一條日誌的等級大於等於這個預設的等級,才會輸出到log檔案中。

當使用logging.info(msg)輸出log時,內部封裝會用數字20作為日誌等級數值,預設情況下20對應的是INFO,但如果通過addLevelName()修改了20對應的等級名稱,那麼log中列印的就將是個人化的等級名稱。

3.logging包使用設定檔

在1~2中描述的,對一個Logger對象的Handler,Formatter等都是在程式中定義或綁定的。而實際上Logging的個人化的配置可以放到設定檔中。

logging的設定檔舉例如下:

[loggers] keys=root,simpleExample  [handlers] keys=consoleHandler  [formatters] keys=simpleFormatter  [logger_root] level=DEBUG handlers=consoleHandler  [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0  [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,)  [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt= 

對應程式為:

import logging  import logging.config    logging.config.fileConfig("logging.conf")  # 採用設定檔     # create logger   logger = logging.getLogger("simpleExample")    # "application" code   logger.debug("debug message")  logger.info("info message")  logger.warn("warn message")  logger.error("error message")  logger.critical("critical message") 

4.一個常用的Logging封裝工具

#!/usr/bin/env python #-*- coding:utf-8 -*- #coding=utf-8  import logging import os  class Logger(object):   """   封裝好的Logger工具   """    def __init__(self, logPath):     """     initial     """     log_path = logPath     logging.addLevelName(20, "NOTICE:")     logging.addLevelName(30, "WARNING:")     logging.addLevelName(40, "FATAL:")     logging.addLevelName(50, "FATAL:")     logging.basicConfig(level=logging.DEBUG,         format="%(levelname)s %(asctime)s [pid:%(process)s] %(filename)s %(message)s",         datefmt="%Y-%m-%d %H:%M:%S",         filename=log_path,         filemode="a")     console = logging.StreamHandler()     console.setLevel(logging.DEBUG)     formatter = logging.Formatter("%(levelname)s [pid:%(process)s] %(message)s")     console.setFormatter(formatter)     logging.getLogger("").addHandler(console)    def debug(self, msg=""):     """     output DEBUG level LOG     """     logging.debug(str(msg))    def info(self, msg=""):     """     output INFO level LOG     """     logging.info(str(msg))    def warning(self, msg=""):     """     output WARN level LOG     """     logging.warning(str(msg))    def exception(self, msg=""):     """     output Exception stack LOG     """     logging.exception(str(msg))    def error(self, msg=""):     """     output ERROR level LOG     """     logging.error(str(msg))    def critical(self, msg=""):     """     output FATAL level LOG     """     logging.critical(str(msg))     if __name__ == "__main__":   testlog = Logger("oupput.log")   testlog.info("info....")   testlog.warning("warning....")   testlog.critical("critical....")   try:     lists = []     print lists[1]   except Exception as ex:     """logging.exception()輸出格式:     FATAL: [pid:7776] execute task failed. the exception as follows:     Traceback (most recent call last):       File "logtool.py", line 86, in <module>         print lists[1]     IndexError: list index out of range     """     testlog.exception("execute task failed. the exception as follows:")     testlog.info("++++++++++++++++++++++++++++++++++++++++++++++")     """logging.error()輸出格式:     FATAL: [pid:7776] execute task failed. the exception as follows:     """     testlog.error("execute task failed. the exception as follows:")     exit(1)

備忘:exception()方法能夠完整的列印異常的堆棧資訊。error()方法只會列印參數傳入的資訊。

備忘:

按照官方文檔的介紹,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.