欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中l(wèi)ogging包的使用總結(jié)

 更新時(shí)間:2018年02月28日 14:25:03   作者:佚名-2017_  
本篇文章給大家詳細(xì)講述了python中l(wèi)ogging包的使用的相關(guān)知識(shí)點(diǎn)以及原理分析,有興趣的朋友可以參考學(xué)習(xí)下。

1.logging 簡介

Python的logging package提供了通用的日志系統(tǒng),可以方便第三方模塊或者是應(yīng)用使用。這個(gè)模塊提供不同的日志級(jí)別,并可以采用不同的方式記錄日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己實(shí)現(xiàn)具體的日志記錄方式。

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

Logger是日志對(duì)象,直接提供日志記錄操作的接口

Formatter定義日志的記錄格式及內(nèi)容

Handler定義日志寫入的目的地,你可以把日志保存成本地文件,也可以每個(gè)小時(shí)寫一個(gè)日志文件,還可以把日志通過socket傳到別的機(jī)器上。python提供了十幾種實(shí)用handler,比較常用的有StreamHandler,BaseRotatingHandler,SocketHandler,DatagramHandler,SMTPHandler等。我們可以通過Logger對(duì)象的addHandler()方法,將log輸出到多個(gè)目的地。

2.Logging package

在python編程中,引入了Logging package,那么可以存在一個(gè)名稱為root的Logging對(duì)象,以及很多其他名稱的Logging對(duì)象。不同的Logger對(duì)象的Handler,F(xiàn)ormatter等是分開設(shè)置的。

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

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

(3)logging.info() logging.debug()等,使用的root Logger對(duì)象進(jìn)行信息輸出。如果是用其他的Logging對(duì)象進(jìn)行l(wèi)og輸出,可以使用Logging.getLogger(name).info()來實(shí)現(xiàn)。

(4)日志的等級(jí)

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

在python中有0,10,20,30,40,50這6個(gè)等級(jí)數(shù)值,這6個(gè)等級(jí)數(shù)值分別對(duì)應(yīng)了一個(gè)字符串常量,作為等級(jí)名稱,如上。但是可以通過logging.addLevelName(20, "NOTICE:")這個(gè)方法來改變這個(gè)映射關(guān)系,來定制化日志等級(jí)名稱。

通過Logger對(duì)象的setLevel()方法,可以配置Logging對(duì)象的默認(rèn)日志等級(jí),只有當(dāng)一條日志的等級(jí)大于等于這個(gè)默認(rèn)的等級(jí),才會(huì)輸出到log文件中。

當(dāng)使用logging.info(msg)輸出log時(shí),內(nèi)部封裝會(huì)用數(shù)字20作為日志等級(jí)數(shù)值,默認(rèn)情況下20對(duì)應(yīng)的是INFO,但如果通過addLevelName()修改了20對(duì)應(yīng)的等級(jí)名稱,那么log中打印的就將是個(gè)性化的等級(jí)名稱。

3.logging包使用配置文件

在1~2中描述的,對(duì)一個(gè)Logger對(duì)象的Handler,F(xiàn)ormatter等都是在程序中定義或綁定的。而實(shí)際上Logging的個(gè)性化的配置可以放到配置文件中。

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= 

對(duì)應(yīng)程序?yàn)椋?/p>

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.一個(gè)常用的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()方法只會(huì)打印參數(shù)傳入的信息。

備注:

按照官方文檔的介紹,logging 是線程安全的,也就是說,在一個(gè)進(jìn)程內(nèi)的多個(gè)線程同時(shí)往同一個(gè)文件寫日志是安全的。但是多個(gè)進(jìn)程往同一個(gè)文件寫日志是不安全的。

相關(guān)文章

最新評(píng)論