Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python logging 模組完全指南:從快速入門到跨檔案全局配置

前言

Python 的 logging 模組為應用程式與函式庫提供了一套靈活的事件日誌系統,它內建多種日誌等級,並支援終端機、檔案等多種輸出目的地。開發任何一套軟體系統時,日誌都是必需品——它記錄函式執行過程,也保存異常拋出的線索。本文是一份學習筆記,對剛開始處理跨檔案模組引用的讀者尤其有幫助。

一、快速入門

先看程式碼。

logt.py

#!/usr/bin/python
# -*- coding:utf-8 -*-
import logging
logging.debug('this is a debug message')
logging.info('this is a info message')
logging.warn('this is a warn message')
logging.error('this is a error message')
logging.critical('this is a critical message')

執行後:

root@rac4:~# python logt.py
WARNING:root:this is a warn message
ERROR:root:this is a error message
CRITICAL:root:this is a critical message

很多人會疑惑:為什麼 debug 和 info 完全沒有輸出? 這就要看日誌等級的設計。

日誌等級

logging 提供五個等級,由低到高分別是:

DEBUG 詳細資訊,排查問題時使用;
INFO 確認事情如預期運作;
WARNING 發生了意外,或近期可能出問題(例如磁碟將滿),但軟體仍可運作;
ERROR 問題較嚴重,部分功能已無法執行;
CRITICAL 嚴重錯誤,程式已無法繼續。

預設門檻是 WARNING,只有等級「高於等於」門檻的訊息才會被輸出,這正是上面 debug/info 消失的原因。輸出方式有兩種:預設印到 console,或改寫入檔案。

logging 的配置方式

Python 提供四種配置途徑:

1. 顯式建立 Logger、Handler、Formatter 並逐一設定;
2. 用 basicConfig() 一行搞定;
3. 用 fileConfig() 讀取設定檔;
4. 用 dictConfig() 讀取字典設定。

本文以 basicConfig() 為例,它支援的常用參數如下:

filename 建立 FileHandler,輸出到指定檔案而非 StreamHandler;
filemode 指定開檔模式,預設 'a'(附加);
format 輸出的格式化字串;
datefmt 時間格式,例如 '%Y-%m-%d %H:%M:%S';
level 指定 logger 的門檻等級;
stream 用指定的串流初始化 StreamHandler,與 filename 互斥。

#!/usr/bin/python
# -*- coding:utf-8 -*-
import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%Y%m%d %H:%M:%S',
                    filename='myapp.log',
                    filemode='w')
logging.info('info message')
logging.warn('warn message')
logging.error('error message')
logging.critical('critical message')

二、進階:四大元件

logging 由四個元件組成:

Logger(記錄器):對應用程式碼提供日誌介面,主要工作是配置與送出訊息。透過 logging.getLogger(name) 取得,不指定 name 則回傳 root;以相同 name 多次呼叫會得到同一個物件。

logger = logging.getLogger(logger_name)   # 不指定則建立 root logger
logger.setLevel(logging.ERROR)            # 只有 >= ERROR 的日誌才輸出
logger.addHandler(handler_name)           # 增加一個處理器
logger.removeHandler(handler_name)        # 移除一個處理器

Handler(處理器):決定日誌送到哪裡,檔案、終端機都可以。一個 logger 可掛多個 handler,每個 handler 還能設各自的等級,从而实现分級分流。

ch = logging.StreamHandler(stream=None)
fh = logging.FileHandler(filename, mode='a', encoding=None, delay=False)

FileHandler 會打開指定檔案作為日誌串流;encoding 不為 None 時以該編碼開檔;delay 為真時延後到第一次 emit() 才真正開檔。

Filter(過濾器):以更優雅的方式決定某筆記錄是否要送往 handler。

Formatter(格式化器):決定輸出的具體格式,建構時接受「訊息格式字串」與「日期字串」兩個可選參數。

接著看一個實用範例 test_log.py,它定義 init_log 函式,同時把日誌送到檔案與終端機:

import logging
import logging.handlers

LOG_LEVELS = {'DEBUG': logging.DEBUG,
              'INFO': logging.INFO,
              'ERROR': logging.ERROR,
              'CRITICAL': logging.CRITICAL}
LOGGING_FORMAT = "%(asctime)s - [%(name)s] - [%(levelname)s] - %(message)s"
STANDARD_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
DEFAULT_LOG_MAX_SIZE = 50 * 1024 * 1024      # 達到 50M 就切分

def init_log(logger_name, level='DEBUG', logfile='/tmp/logtest.log',
             formatter=LOGGING_FORMAT, max_size=DEFAULT_LOG_MAX_SIZE):
    logger = logging.getLogger('')            # 初始化 logging 實例
    logger.setLevel(LOG_LEVELS[level])        # 設定日誌等級
    fh = logging.handlers.RotatingFileHandler(logfile, maxBytes=max_size, backupCount=3)
    fh.setLevel(logging.DEBUG)                # 輸出到檔案的 handler
    ch = logging.StreamHandler()              # 輸出到終端的 handler
    ch.setLevel(logging.INFO)
    formatter = logging.Formatter(formatter)
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    logger.addHandler(fh)
    logger.addHandler(ch)
    return logging.getLogger(logger_name)

if __name__ == '__main__':
    LOGGER = init_log('youzan', 'INFO', '0614.log')
    LOGGER.info('info message')
    LOGGER.warn('warn message')
    LOGGER.error('error message')
    LOGGER.critical('critical message')

執行結果(終端與 0614.log 內容一致):

2016-06-14 10:38:15,190 - [youzan] - [INFO] - info message
2016-06-14 10:38:15,190 - [youzan] - [WARNING] - warn message
2016-06-14 10:38:15,191 - [youzan] - [ERROR] - error message
2016-06-14 10:38:15,191 - [youzan] - [CRITICAL] - critical message

三、進階應用:跨檔案共用配置

這才是重點:真實專案裡,如何把 logging 配置集中在一個模組,讓各個程式檔都能共用?目錄結構如下:

.
├── log2.py        -- 引用 logconfig 中的 logging 配置
└── logconfig.py   -- 配置 logging 輸出格式

特別注意:若要跨檔案引用 logconfig,必須在 logconfig.py 所在目錄建立 __init__.py,讓它成為套件。

log2.py:

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import logging
from logconfig import init_log

logger = init_log('logtest', 'INFO', log='666.log')   # 傳參決定新的配置
logger.info('this is a test %s', " yangyi@youzan.com")
logger.debug('debug message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

執行結果:

root@rac4:~# python log2.py
2016-06-14 13:26:50,713 - [logtest] - [INFO] - this is a test yangyi@youzan.com
2016-06-14 13:26:50,713 - [logtest] - [WARNING] - warn message
2016-06-14 13:26:50,714 - [logtest] - [ERROR] - error message
2016-06-14 13:26:50,714 - [logtest] - [CRITICAL] - critical message

可以看到 debug 因為低於 INFO 門檻而被過濾,其餘訊息同時落到終端與檔案,這就是一套可重複使用的日誌基礎設施該有的樣子。

延伸閱讀:CentOS 源碼安裝 Python3.4 https://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》 https://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》 https://www.linuxidc.com/Linux/2013-11/92693.htm

Python 腳本獲取 Linux 系統資訊 https://www.linuxidc.com/Linux/2013-08/88531.htm

Python 語言的發展簡史 https://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved