国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python中logging包的使用總結

2020-01-04 15:47:10
字體:
來源:轉載
供稿:網友

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 是線程安全的,也就是說,在一個進程內的多個線程同時往同一個文件寫日志是安全的。但是多個進程往同一個文件寫日志是不安全的。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安吉县| 凤山市| 汶川县| 卓资县| 喀喇| 元谋县| 琼中| 鄄城县| 五峰| 武乡县| 太和县| 商丘市| 绿春县| 万源市| 英德市| 延川县| 上思县| 汝城县| 新沂市| 屯留县| 郸城县| 吐鲁番市| 闽侯县| 罗城| 云浮市| 隆子县| 东乡| 徐水县| 磴口县| 花莲市| 乌兰察布市| 兖州市| 和平区| 成安县| 敖汉旗| 彩票| 赣州市| 光泽县| 张掖市| 泗洪县| 浠水县|