python的logging兩種高級用法

一、 基礎使用

1.1 logging使用場景

日誌是什麼?這個不用多解釋。百分之九十的程序都需要提供日誌功能。Python內置的logging模塊,爲我們提供了現成的高效好用的日誌解決方案。但是,不是所有的場景都需要使用logging模塊,下面是Python官方推薦的使用方法:

任務場景 最佳工具
普通情況下,在控制檯顯示輸出 print()
報告正常程序操作過程中發生的事件 logging.info()(或者更詳細的logging.debug())
發出有關特定事件的警告 warnings.warn()或者logging.warning()
報告錯誤 彈出異常
在不引發異常的情況下報告錯誤 logging.error()logging.exception()或者logging.critical()

1.2 簡單範例

在什麼都不配置和設定的情況下,logging會簡單地將日誌打印在顯示器上,如下例所示:

import logging
logging.warning('Watch out!')  # 消息會被打印到控制檯上
logging.info('I told you so')  # 這行不會被打印,因爲級別低於默認級別

如果,將上面的代碼放在一個腳本里並運行,結果是:

WARNING:root:Watch out!

二、python的logging兩種高級用法

如果只是簡單地使用logging,那麼使用上面介紹的方法就可以了,如果要深度定製logging,那麼就需要對它有更深入的瞭解。下面的內容纔是基本的logging模塊的使用方法。

logging模塊採用了模塊化設計,主要包含四種組件:

Loggers:記錄器,提供應用程序代碼能直接使用的接口;

Handlers:處理器,將記錄器產生的日誌發送至目的地;

Filters:過濾器,提供更好的粒度控制,決定哪些日誌會被輸出;

Formatters:格式化器,設置日誌內容的組成結構和消息字段。

下面是兩種流程:屏幕和文件進行日誌輸出

1、屏幕進行日誌輸出

標準輸出stdout(如顯示器)分發器。

創建方法: sh = logging.StreamHandler(stream=None)

#simple_logging_module.py
# -*- coding: utf-8 -*-
import logging

# 創建logger記錄器
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# 創建一個控制檯處理器,並將日誌級別設置爲debug。
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# 創建formatter格式化器
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# 將formatter添加到ch處理器
ch.setFormatter(formatter)

# 將ch添加到logger
logger.addHandler(ch)

# 然後就可以開始使用了!
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

輸出結果:打印在屏幕

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/owen_logging.py
2019-11-14 10:11:59,673 - simple_example - DEBUG - debug message
2019-11-14 10:11:59,673 - simple_example - INFO - info message
2019-11-14 10:11:59,673 - simple_example - WARNING - warn message
2019-11-14 10:11:59,673 - simple_example - ERROR - error message
2019-11-14 10:11:59,673 - simple_example - CRITICAL - critical message

2、文件進行日誌輸出

將日誌保存到磁盤文件的處理器。

創建方法: fh = logging.FileHandler(filename, mode='a', encoding=None, delay=False)

#simple_logging_module.py
# -*- coding: utf-8 -*-
import logging

# 創建logger記錄器
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# 創建一個文本處理器,並將日誌級別設置爲debug。
fh = logging.FileHandler('test.log')
fh.setLevel(logging.DEBUG)

# 創建formatter格式化器
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# 將formatter添加到ch處理器
fh.setFormatter(formatter)

# 將fh添加到logger
logger.addHandler(fh)

# 然後就可以開始使用了!
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

輸出結果:

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