Python標準庫系列之logging模塊
This module defines functions and classes which implement a flexible event logging system for applications and libraries.
The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging, so your application log can include your own messages integrated with messages from third-party modules.
官方文檔:https://docs.python.org/3.5/library/logging.html
logging模塊用於便捷記錄日誌且線程安全。
日誌級別
Level | Numeric value |
---|---|
CRITICAL | 50 |
ERROR | 40 |
WARNING | 30 |
INFO | 20 |
DEBUG | 10 |
NOTSET | 0 |
只有大於當前日誌等級的操作纔會被記錄。
實例
寫入單文件
代碼
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # 導入logging模塊 import logging # 創建一個log.log日誌文件 logging.basicConfig(filename='log.log', # 格式化的字符串 format='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s', # 時間 datefmt='%Y-%m-%d %H:%M:%S %p', # 錯誤級別 level=logging.NOTSET ) logging.critical('critical') logging.error('error') logging.warning('warning') logging.info('info') logging.debug('debug') logging.log(logging.INFO, 'NOTSET')
執行結果
ansheng@ansheng-me:~$ ls log.py ansheng@ansheng-me:~$ python log.py ansheng@ansheng-me:~$ ls log.log log.py ansheng@ansheng-me:~$ cat log.log 2016-05-27 21:46:15 PM - root - CRITICAL - log: critical 2016-05-27 21:46:15 PM - root - ERROR - log: error 2016-05-27 21:46:15 PM - root - WARNING - log: warning 2016-05-27 21:46:15 PM - root - INFO - log: info 2016-05-27 21:46:15 PM - root - DEBUG - log: debug 2016-05-27 21:46:15 PM - root - INFO - log: NOTSET
logging.basicConfig函數各參數
參數 | 說明 |
---|---|
filename | 指定日誌文件名 |
filemode | 和file函數意義相同,指定日誌文件的打開模式,’w’或’a’ |
format | 指定輸出的格式和內容,format可以輸出很多有用信息,如下所示 |
datefmt | 指定時間格式,同time.strftime() |
level | 設置日誌級別,默認爲logging.WARNING |
format參數
參數 | 說明 |
---|---|
%(levelno)s | 打印日誌級別的數值 |
%(levelname)s | 打印日誌級別名稱 |
%(pathname)s | 打印當前執行程序的路徑,其實就是sys.argv[0] |
%(filename)s | 打印當前執行程序名 |
%(funcName)s | 打印日誌的當前函數 |
%(lineno)d | 打印日誌的當前行號 |
%(asctime)s | 打印日誌的時間 |
%(thread)d | 打印線程ID |
%(threadName)s | 打印線程名稱 |
%(process)d | 打印進程ID |
%(message)s | 打印日誌信息 |
多文件日誌
對於上述記錄日誌的功能,只能將日誌記錄在單文件中,如果想要設置多個日誌文件,logging.basicConfig將無法完成,需要自定義文件和日誌操作對象。
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import logging # 創建文件 file_1 = logging.FileHandler("log1.log", "a") # 創建寫入的日誌格式 fmt1 = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(module)s : %(message)s") # 文件用格式 file_1.setFormatter(fmt1) file_2 = logging.FileHandler("log2.log", "a") fmt2 = logging.Formatter() file_2.setFormatter(fmt2) logger1 = logging.Logger("s1", level=logging.ERROR) logger1.addHandler(file_1) logger1.addHandler(file_2) logger1.critical("1111")
# 定義文件 file_2_1 = logging.FileHandler('l2_1.log', 'a') fmt = logging.Formatter() file_2_1.setFormatter(fmt) # 定義日誌 logger2 = logging.Logger('s2', level=logging.INFO) logger2.addHandler(file_2_1)
如上述創建的兩個日誌對象
當使用
logger1
寫日誌時,會將相應的內容寫入 l1_1.log 和 l1_2.log 文件中當使用
logger2
寫日誌時,會將相應的內容寫入 l2_1.log 文件中