天天看點

python logging子產品

概述:

python的logging子產品提供了标準的日志接口,你可以通過它存儲各種格式的日志,logging的日志可以分為 

debug()

info()

warning()

error()

 and 

critical() 5個級别。

logging 日志資訊的簡單用法

預設的,日志級别要高于INFO級别才會有内容輸出。

import logging

logging.debug("user[root] this is a {debug} message..")
logging.info("user[root] this is a {info} message..")
logging.warning("The server is down. this is a {warning} message..")
logging.error("the password is error,con't to login . this is a {error} message..")
logging.critical("user[root] this is a critical message..")

"""
WARNING:root:The server is down. this is a {warning} message..
ERROR:root:the password is error,con't to login . this is a {error} message..
CRITICAL:root:user[root] this is a critical message..
"""
      

logging 5個日志級别代表的意思:

python logging子產品

将logging日志資訊寫到檔案内

logging.basicConfig函數對日志的輸出格式及方式做相關配置,level 設定日志輸出的級别,farmat 設定日志儲存的格式,datefmt 設定日志時間的格式,filename日志儲存檔案的名稱,filemode檔案輸入的模式:“a”為追加。

import logging

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename="myLOG.log",
                    filemode="a")
logging.debug('This message should go to the log file')
logging.info('So should this,info log')
logging.warning('This is warning message')
      

MyLOG.log文檔中日志資訊:

Thu, 17 Aug 2017 15:59:10 log_v1.py[line:55] INFO So should this,info log
Thu, 17 Aug 2017 15:59:10 log_v1.py[line:56] WARNING This is warning message
Thu, 17 Aug 2017 15:59:57 log_v1.py[line:55] INFO So should this,info log
Thu, 17 Aug 2017 15:59:57 log_v1.py[line:56] WARNING This is warning message
      

 logging日志格式:

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

将logging日志輸出到螢幕和檔案中

Python 使用logging子產品記錄日志涉及四個主要類:

logger提供了應用程式可以直接使用的接口;

handler将(logger建立的)日志記錄發送到合适的目的輸出;

filter提供了細度裝置來決定輸出哪條日志記錄;

formatter決定日志記錄的最終輸出格式。
      

   logger接口:

Logger通常對應了程式的子產品名,比如聊天工具的圖形界面子產品可以這樣獲得它的Logger:

LOG=logging.getLogger(”chat.gui”)

而核心子產品可以這樣:

LOG=logging.getLogger(”chat.kernel”)

Logger.setLevel(lel):指定最低的日志級别,低于lel的級别将被忽略。debug是最低的内置級别,critical為最高

Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter

Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler

Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以設定的日志級别

  handler:

handler對象負責發送相關的資訊到指定目的地。Python的日志系統有多種Handler可以使用。有些Handler可以把資訊輸出到控制台,有些Logger可以把資訊輸出到檔案,還有些 Handler可以把資訊發送到網絡上。如果覺得不夠用,還可以編寫自己的Handler。可以通過addHandler()方法添加多個多handler

Handler.setLevel(lel):指定被處理的資訊級别,低于lel級别的資訊将被忽略

Handler.setFormatter():給這個handler選擇一個格式

Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一個filter對象

每個Logger可以附加多個Handler。接下來我們就來介紹一些常用的Handler:

1) logging.StreamHandler

使用這個Handler可以向類似與sys.stdout或者sys.stderr的任何檔案對象(file object)輸出資訊。它的構造函數是:

StreamHandler([strm])

其中strm參數是一個檔案對象。預設是sys.stderr

2) logging.FileHandler

和StreamHandler類似,用于向一個檔案輸出日志資訊。不過FileHandler會幫你打開這個檔案。它的構造函數是:

FileHandler(filename[,mode])

filename是檔案名,必須指定一個檔案名。

mode是檔案的打開方式。參見Python内置函數open()的用法。預設是’a',即添加到檔案末尾。

3) logging.handlers.RotatingFileHandler

這個Handler類似于上面的FileHandler,但是它可以管理檔案大小。當檔案達到一定大小之後,它會自動将目前日志檔案改名,然後建立 一個新的同名日志檔案繼續輸出。比如日志檔案是chat.log。當chat.log達到指定的大小之後,RotatingFileHandler自動把 檔案改名為chat.log.1。不過,如果chat.log.1已經存在,會先把chat.log.1重命名為chat.log.2。。。最後重新建立 chat.log,繼續輸出日志資訊。它的構造函數是:

RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])

其中filename和mode兩個參數和FileHandler一樣。

maxBytes用于指定日志檔案的最大檔案大小。如果maxBytes為0,意味着日志檔案可以無限大,這時上面描述的重命名過程就不會發生。

backupCount用于指定保留的備份檔案的個數。比如,如果指定為2,當上面描述的重命名過程發生時,原有的chat.log.2并不會被更名,而是被删除。

4) logging.handlers.TimedRotatingFileHandler

這個Handler和RotatingFileHandler類似,不過,它沒有通過判斷檔案大小來決定何時重新建立日志檔案,而是間隔一定時間就 自動建立新的日志檔案。重命名的過程與RotatingFileHandler類似,不過新的檔案不是附加數字,而是目前時間。它的構造函數是:

TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])

其中filename參數和backupCount參數和RotatingFileHandler具有相同的意義。

interval是時間間隔。

when參數是一個字元串。表示時間間隔的機關,不區分大小寫。它有以下取值:

S 秒

M 分

H 小時

D 天

W 每星期(interval==0時代表星期一)

midnight 每天淩晨

# 例1:

import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename="myapp.log",
                    filemode="a")  #輸出到文檔

console = logging.StreamHandler() # 定義一個StreamHandler,将INFO級别或更高的日志資訊列印到标準錯誤,并将其添加到目前的日志處理對象
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)-12s:%(levelname)-8s %(message)s')   # 螢幕輸出
console.setFormatter(formatter)
logging.getLogger("").addHandler(console)

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
      

# 例2(另一種經典寫法):

import logging

logger = logging.getLogger("logger")
logger.setLevel(logging.DEBUG)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

fh = logging.FileHandler("mylog.log")
fh.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

ch.setFormatter(formatter)
fh.setFormatter(formatter)

logger.addHandler(ch)
logger.addHandler(fh)


# 日志資訊
logger.debug('this is debug message')
logger.info('this is info message')
logger.warn('this is warning message')
logger.error('this is error message')
logger.critical('this is critical message')
      

螢幕輸出的日志資訊:

2017-08-17 16:39:55,971 - logger - DEBUG - this is debug message
2017-08-17 16:39:55,971 - logger - INFO - this is info message
2017-08-17 16:39:55,971 - logger - WARNING - this is warning message
2017-08-17 16:39:55,971 - logger - ERROR - this is error message
2017-08-17 16:39:55,971 - logger - CRITICAL - this is critical message
      
mylog.log檔案中的日志資訊:      
2017-08-17 16:41:49,346 - logger - DEBUG - this is debug message
2017-08-17 16:41:49,346 - logger - INFO - this is info message
2017-08-17 16:41:49,346 - logger - WARNING - this is warning message
2017-08-17 16:41:49,346 - logger - ERROR - this is error message
2017-08-17 16:41:49,346 - logger - CRITICAL - this is critical message      

  

通過配置檔案配置logger:

定義配置檔案logger.conf

#logger.conf
###############################################
[loggers]
keys=root,example01,example02
[logger_root]
level=DEBUG
handlers=hand01,hand02
[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0
[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0
###############################################

[handlers]
keys=hand01,hand02,hand03
[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')
[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('myapp.log', 'a', 10*1024*1024, 5)
###############################################
[formatters]
keys=form01,form02
[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S
[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=
      

擷取logging.config配置的日志:

import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")

logger.debug("this is debug message")
logger.info('This is info message')
logger.warning('This is warning message')
      

日志輸出結果:

example01   : INFO     This is info message
example01   : WARNING  This is warning message
      

參考連結1:http://www.cnblogs.com/tkqasn/p/6020282.html

參考連結2:http://www.cnblogs.com/alex3714/articles/5161349.html

上一篇: js 函數
下一篇: rpm 指令詳解