logging模塊(三)—— logging日誌框架自定義日誌模塊

(一)logging日誌框架組成部分

  • Logger:記錄器。即 Logger Main Class,是我們進行日誌記錄時創建的對象,我們可以調用它的方法傳入日誌模板和信息,來生成一條條日誌記錄,稱作 Log Record。
  • Handler:處理器。即用來處理日誌記錄的類,它可以將 Log Record 輸出到我們指定的日誌位置和存儲形式等,如我們可以指定將日誌通過 FTP 協議記錄到遠程的服務器上,Handler 就會幫我們完成這些事情。
  • Formatter:-格式化。實際上生成的 Log Record 也是一個個對象,那麼我們想要把它們保存成一條條我們想要的日誌文本的話,就需要有一個格式化的過程,那麼這個過程就由 Formatter 來完成,返回的就是日誌字符串,然後傳回給 Handler 來處理。
  • Filter:篩選器。另外保存日誌的時候我們可能不需要全部保存,我們可能只需要保存我們想要的部分就可以了,所以保存前還需要進行一下過濾,留下我們想要的日誌,如只保存某個級別的日誌,或只保存包含某個關鍵字的日誌等,那麼這個過濾過程就交給 Filter 來完成。

(二)寫入日誌文件主要流程:

  1. 創建一個logger對象
  2. 設置日誌級別level
  3. 創建一個handler,用於寫入日誌文件
  4. 設置handler輸出格式formatter
  5. 將filter過濾後的logger發給handler

(三)實例:

使用logging日誌模塊記錄日誌文件

'''
logging日誌框架-logger,formatter,filter,handler
'''

import logging

#創建一個logger對象
logger = logging.getLogger()

#設置logger日誌級別
logger.setLevel(logging.NOTSET)

#設置日誌去向
handler=logging.FileHandler(filename='study02.log', encoding='utf-8',)

#設置實際輸入到日誌文件的日誌級別
handler.setLevel(logging.ERROR)

#設置日誌格式
formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

#給logger對象添加日誌去向
logger.addHandler(handler)

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
logger.error('this is error message')
logger.critical('this is cirtical message')




 

 

(四)擴展

Loggers:

Logger 對象要做三件事情。

首先,它們嚮應用代碼暴露了許多方法,這樣應用可以在運行時記錄消息。

其次,記錄器對象通過嚴重程度(默認的過濾設施)或者過濾器對象來決定哪些日誌消息需要記錄下來。

第三,記錄器對象將相關的日誌消息傳遞給所有感興趣的日誌處理器。

常用的記錄器對象的方法分爲兩類:配置和發送消息。

這些是最常用的配置方法:

Logger.setLevel()指定logger將會處理的最低的安全等級日誌信息。

Logger.addHandler()從記錄器對象中添加處理程序對象。

Logger.addFilter()從記錄器對象添加過濾器對象。

Handlers

處理程序對象負責將適當的日誌消息(基於日誌消息的嚴重性)分派到處理程序的指定目標。

Logger 對象可以通過addHandler()方法增加零個或多個handler對象。舉個例子,一個應用可以將所有的日誌消息發送至日誌文件,所有的錯誤級別(error)及以上的日誌消息發送至標準輸出,所有的嚴重級別(critical)日誌消息發送至某個電子郵箱。在這個例子中需要三個獨立的處理器,每一個負責將特定級別的消息發送至特定的位置。

常用的有4種: 

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是文件的打開方式。默認是’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 每天凌晨

 

Formatter

Attribute name

Format

Description

args

You shouldn’t need to format this yourself.

The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).

asctime

%(asctime)s

Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).

created

%(created)f

Time when the LogRecord was created (as returned by time.time()).

exc_info

You shouldn’t need to format this yourself.

Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.

filename

%(filename)s

Filename portion of pathname.

funcName

%(funcName)s

Name of function containing the logging call.

levelname

%(levelname)s

Text logging level for the message ('DEBUG''INFO''WARNING''ERROR''CRITICAL').

levelno

%(levelno)s

Numeric logging level for the message (DEBUGINFOWARNINGERRORCRITICAL).

lineno

%(lineno)d

Source line number where the logging call was issued (if available).

message

%(message)s

The logged message, computed as msg % args. This is set when Formatter.format() is invoked.

module

%(module)s

Module (name portion of filename).

msecs

%(msecs)d

Millisecond portion of the time when the LogRecord was created.

msg

You shouldn’t need to format this yourself.

The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).

name

%(name)s

Name of the logger used to log the call.

pathname

%(pathname)s

Full pathname of the source file where the logging call was issued (if available).

process

%(process)d

Process ID (if available).

processName

%(processName)s

Process name (if available).

relativeCreated

%(relativeCreated)d

Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.

stack_info

You shouldn’t need to format this yourself.

Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.

thread

%(thread)d

Thread ID (if available).

threadName

%(threadName)s

Thread name (if available).

 

 


官網:https://docs.python.org/3.8/library/logging.html#module-logging

參考地址:https://www.cnblogs.com/nancyzhu/p/8551506.html

gitbuh地址: https://github.com/panc-test/python-study.git

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章