1. 程式人生 > >Python日誌logging模塊

Python日誌logging模塊

顯示 dha class 逗號 spa efm mode 記錄 title

很多程序都有記錄日誌的需求,並且日誌中包含的信息即有正常的程序訪問日誌,還可能有錯誤、警告等信息輸出,python的logging模塊提供了標準的日誌接口,你可以通過它存儲各種格式的日誌,logging的日誌可以分為 debug(), info(), warning(), error() and critical() 5個級別,下面我們看一下怎麽用。

一.最簡單用法

import logging
logging.debug(debug message)
logging.info(info message)
logging.warning(warning message)
logging.error(
error message) logging.critical(critical message) #WARNING:root:warning message #ERROR:root:error message #CRITICAL:root:critical message 默認只顯示warning以上的日誌

二.修改默認配置

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=/tmp/test.log, #日誌保存的位置,如果這裏不加filename,會以答應的形式顯示出來,而不會保存 filemode=w) #這裏是w會重新覆蓋,a是追加 logging.debug(debug message) logging.info(info message) logging.warning(
warning message) logging.error(error message) logging.critical(critical message)

 1 format參數中可能用到的格式化串:
 2 %(name)s Logger的名字
 3 %(levelno)s 數字形式的日誌級別
 4 %(levelname)s 文本形式的日誌級別
 5 %(pathname)s 調用日誌輸出函數的模塊的完整路徑名,可能沒有
 6 %(filename)s 調用日誌輸出函數的模塊的文件名
 7 %(module)s 調用日誌輸出函數的模塊名
 8 %(funcName)s 調用日誌輸出函數的函數名
 9 %(lineno)d 調用日誌輸出函數的語句所在的代碼行
10 %(created)f 當前時間,用UNIX標準的表示時間的浮 點數表示
11 %(relativeCreated)d 輸出日誌信息時的,自Logger創建以 來的毫秒數
12 %(asctime)s 字符串形式的當前時間。默認格式是 “2003-07-08 16:49:45,896”。逗號後面的是毫秒
13 %(thread)d 線程ID。可能沒有
14 %(threadName)s 線程名。可能沒有
15 %(process)d 進程ID。可能沒有
16 %(message)s用戶輸出的消息


三.同步顯示

這裏出現一個問題,日誌只能要麽打印要麽保存,只能選擇一個,我們改進一下

import logging

logger = logging.getLogger()
# 創建一個handler,用於寫入日誌文件
fh = logging.FileHandler(test.log)

# 再創建一個handler,用於輸出到控制臺
ch = logging.StreamHandler()

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

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

logger.addHandler(fh) #logger對象可以添加多個fh和ch對象
logger.addHandler(ch)

logger.setLevel(logging.Debug) logger.debug(
logger debug message) logger.info(logger info message) logger.warning(logger warning message) logger.error(logger error message) logger.critical(logger critical message)

技術分享

logging庫提供了多個組件:

  Logger對象提供應用程序可直接使用的接口

  Handler發送日誌到適當的目的地

  Filter提供了過濾日誌信息的方法

  Formatter指定日誌顯示格式。

Python日誌logging模塊