1. 程式人生 > >Python模塊學習--logging

Python模塊學習--logging

事件日誌 nco .json 執行 fat 處理請求 logging模塊 Coding sage

1 logging模塊簡介

logging模塊是Python內置的標準模塊,主要用於輸出運行日誌,可以設置輸出日誌的等級、日誌保存路徑、日誌文件回滾等;相比print,具備如下優點:

  1. 可以通過設置不同的日誌等級,在release版本中只輸出重要信息,而不必顯示大量的調試信息;
  2. print將所有信息都輸出到標準輸出中,嚴重影響開發者從標準輸出中查看其它數據;logging則可以由開發者決定將信息輸出到什麽地方,以及怎麽輸出;

2 logging模塊使用

2.1 基本使用

配置logging基本的設置,然後在控制臺輸出日誌,

import logging
logging.basicConfig(level = logging.INFO,format = ‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
logger = logging.getLogger(__name__)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")

運行時,控制臺輸出,

2016-10-09 19:11:19,434 - __main__ - INFO - Start print log
2016-10-09 19:11:19,434 - __main__ - WARNING - Something maybe fail.
2016-10-09 19:11:19,434 - __main__ - INFO - Finish

logging中可以選擇很多消息級別,如debug、info、warning、error以及critical。通過賦予logger或者handler不同的級別,開發者就可以只輸出錯誤信息到特定的記錄文件,或者在調試時只記錄調試信息。

例如,我們將logger的級別改為DEBUG,再觀察一下輸出結果,

logging.basicConfig(level = logging.DEBUG,format = ‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)

控制臺輸出,可以發現,輸出了debug的信息。

2016-10-09 19:12:08,289 - __main__ - INFO - Start print log
2016-10-09 19:12:08,289 - __main__ - DEBUG - Do something
2016-10-09 19:12:08,289 - __main__ - WARNING - Something maybe fail.
2016-10-09 19:12:08,289 - __main__ - INFO - Finish

logging.basicConfig函數各參數:

filename:指定日誌文件名;

filemode:和file函數意義相同,指定日誌文件的打開模式,‘w‘或者‘a‘;

format:指定輸出的格式和內容,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:打印日誌信息

datefmt:指定時間格式,同time.strftime();

level:設置日誌級別,默認為logging.WARNNING;

stream:指定將日誌的輸出流,可以指定輸出到sys.stderr,sys.stdout或者文件,默認輸出到sys.stderr,當stream和filename同時指定時,stream被忽略;

2.2 將日誌寫入到文件

2.2.1 將日誌寫入到文件

設置logging,創建一個FileHandler,並對輸出消息的格式進行設置,將其添加到logger,然後將日誌寫入到指定的文件中,

import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")

log.txt中日誌數據為,

2016-10-09 19:01:13,263 - __main__ - INFO - Start print log
2016-10-09 19:01:13,263 - __main__ - WARNING - Something maybe fail.
2016-10-09 19:01:13,263 - __main__ - INFO - Finish

2.2.2 將日誌同時輸出到屏幕和日誌文件

logger中添加StreamHandler,可以將日誌輸出到屏幕上,

import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)

logger.addHandler(handler)
logger.addHandler(console)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")

可以在log.txt文件和控制臺中看到,

2016-10-09 19:20:46,553 - __main__ - INFO - Start print log
2016-10-09 19:20:46,553 - __main__ - WARNING - Something maybe fail.
2016-10-09 19:20:46,553 - __main__ - INFO - Finish

可以發現,logging有一個日誌處理的主對象,其他處理方式都是通過addHandler添加進去,logging中包含的handler主要有如下幾種,

handler名稱:位置;作用

StreamHandler:logging.StreamHandler;日誌輸出到流,可以是sys.stderr,sys.stdout或者文件
FileHandler:logging.FileHandler;日誌輸出到文件
BaseRotatingHandler:logging.handlers.BaseRotatingHandler;基本的日誌回滾方式
RotatingHandler:logging.handlers.RotatingHandler;日誌回滾方式,支持日誌文件最大數量和日誌文件回滾
TimeRotatingHandler:logging.handlers.TimeRotatingHandler;日誌回滾方式,在一定時間區域內回滾日誌文件
SocketHandler:logging.handlers.SocketHandler;遠程輸出日誌到TCP/IP sockets
DatagramHandler:logging.handlers.DatagramHandler;遠程輸出日誌到UDP sockets
SMTPHandler:logging.handlers.SMTPHandler;遠程輸出日誌到郵件地址
SysLogHandler:logging.handlers.SysLogHandler;日誌輸出到syslog
NTEventLogHandler:logging.handlers.NTEventLogHandler;遠程輸出日誌到Windows NT/2000/XP的事件日誌
MemoryHandler:logging.handlers.MemoryHandler;日誌輸出到內存中的指定buffer
HTTPHandler:logging.handlers.HTTPHandler;通過"GET"或者"POST"遠程輸出到HTTP服務器

2.2.3 日誌回滾

使用RotatingFileHandler,可以實現日誌回滾,

import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
#定義一個RotatingFileHandler,最多備份3個日誌文件,每個日誌文件最大1K
rHandler = RotatingFileHandler("log.txt",maxBytes = 1*1024,backupCount = 3)
rHandler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
rHandler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)

logger.addHandler(rHandler)
logger.addHandler(console)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")

可以在工程目錄中看到,備份的日誌文件,

2016/10/09  19:36               732 log.txt
2016/10/09  19:36               967 log.txt.1
2016/10/09  19:36               985 log.txt.2
2016/10/09  19:36               976 log.txt.3

2.3 設置消息的等級

可以設置不同的日誌等級,用於控制日誌的輸出,

日誌等級:使用範圍

FATAL:致命錯誤
CRITICAL:特別糟糕的事情,如內存耗盡、磁盤空間為空,一般很少使用
ERROR:發生錯誤時,如IO操作失敗或者連接問題
WARNING:發生很重要的事件,但是並不是錯誤時,如用戶登錄密碼錯誤
INFO:處理請求或者狀態變化等日常事務
DEBUG:調試過程中使用DEBUG等級,如算法中每個循環的中間狀態

2.4 捕獲traceback

Python中的traceback模塊被用於跟蹤異常返回信息,可以在logging中記錄下traceback,

代碼,

import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)

logger.addHandler(handler)
logger.addHandler(console)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
try:
    open("sklearn.txt","rb")
except (SystemExit,KeyboardInterrupt):
    raise
except Exception:
    logger.error("Faild to open sklearn.txt from logger.error",exc_info = True)

logger.info("Finish")

控制臺和日誌文件log.txt中輸出,

Start print log
Something maybe fail.
Faild to open sklearn.txt from logger.error
Traceback (most recent call last):
  File "G:\zhb7627\Code\Eclipse WorkSpace\PythonTest\test.py", line 23, in <module>
    open("sklearn.txt","rb")
IOError: [Errno 2] No such file or directory: ‘sklearn.txt‘
Finish

也可以使用logger.exception(msg,_args),它等價於logger.error(msg,exc_info = True,_args),

logger.error("Faild to open sklearn.txt from logger.error",exc_info = True)

替換為,

logger.exception("Failed to open sklearn.txt from logger.exception")

控制臺和日誌文件log.txt中輸出,

Start print log
Something maybe fail.
Failed to open sklearn.txt from logger.exception
Traceback (most recent call last):
  File "G:\zhb7627\Code\Eclipse WorkSpace\PythonTest\test.py", line 23, in <module>
    open("sklearn.txt","rb")
IOError: [Errno 2] No such file or directory: ‘sklearn.txt‘
Finish

2.5 多模塊使用logging

主模塊mainModule.py,

import logging
import subModule
logger = logging.getLogger("mainModule")
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)

logger.addHandler(handler)
logger.addHandler(console)


logger.info("creating an instance of subModule.subModuleClass")
a = subModule.SubModuleClass()
logger.info("calling subModule.subModuleClass.doSomething")
a.doSomething()
logger.info("done with  subModule.subModuleClass.doSomething")
logger.info("calling subModule.some_function")
subModule.som_function()
logger.info("done with subModule.some_function")

子模塊subModule.py,

import logging

module_logger = logging.getLogger("mainModule.sub")
class SubModuleClass(object):
    def __init__(self):
        self.logger = logging.getLogger("mainModule.sub.module")
        self.logger.info("creating an instance in SubModuleClass")
    def doSomething(self):
        self.logger.info("do something in SubModule")
        a = []
        a.append(1)
        self.logger.debug("list a = " + str(a))
        self.logger.info("finish something in SubModuleClass")

def som_function():
    module_logger.info("call function some_function")

執行之後,在控制和日誌文件log.txt中輸出,

2016-10-09 20:25:42,276 - mainModule - INFO - creating an instance of subModule.subModuleClass
2016-10-09 20:25:42,279 - mainModule.sub.module - INFO - creating an instance in SubModuleClass
2016-10-09 20:25:42,279 - mainModule - INFO - calling subModule.subModuleClass.doSomething
2016-10-09 20:25:42,279 - mainModule.sub.module - INFO - do something in SubModule
2016-10-09 20:25:42,279 - mainModule.sub.module - INFO - finish something in SubModuleClass
2016-10-09 20:25:42,279 - mainModule - INFO - done with  subModule.subModuleClass.doSomething
2016-10-09 20:25:42,279 - mainModule - INFO - calling subModule.some_function
2016-10-09 20:25:42,279 - mainModule.sub - INFO - call function some_function
2016-10-09 20:25:42,279 - mainModule - INFO - done with subModule.some_function

首先在主模塊定義了logger‘mainModule‘,並對它進行了配置,就可以在解釋器進程裏面的其他地方通過getLogger(‘mainModule‘)得到的對象都是一樣的,不需要重新配置,可以直接使用。定義的該logger的子logger,都可以共享父logger的定義和配置,所謂的父子logger是通過命名來識別,任意以‘mainModule‘開頭的logger都是它的子logger,例如‘mainModule.sub‘。

實際開發一個application,首先可以通過logging配置文件編寫好這個application所對應的配置,可以生成一個根logger,如‘PythonAPP‘,然後在主函數中通過fileConfig加載logging配置,接著在application的其他地方、不同的模塊中,可以使用根logger的子logger,如‘PythonAPP.Core‘,‘PythonAPP.Web‘來進行log,而不需要反復的定義和配置各個模塊的logger。

3 通過JSON或者YAML文件配置logging模塊

盡管可以在Python代碼中配置logging,但是這樣並不夠靈活,最好的方法是使用一個配置文件來配置。在Python 2.7及以後的版本中,可以從字典中加載logging配置,也就意味著可以通過JSON或者YAML文件加載日誌的配置。

3.1 通過JSON文件配置

JSON配置文件,

{
    "version":1,
    "disable_existing_loggers":false,
    "formatters":{
        "simple":{
            "format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    },
    "handlers":{
        "console":{
            "class":"logging.StreamHandler",
            "level":"DEBUG",
            "formatter":"simple",
            "stream":"ext://sys.stdout"
        },
        "info_file_handler":{
            "class":"logging.handlers.RotatingFileHandler",
            "level":"INFO",
            "formatter":"simple",
            "filename":"info.log",
            "maxBytes":"10485760",
            "backupCount":20,
            "encoding":"utf8"
        },
        "error_file_handler":{
            "class":"logging.handlers.RotatingFileHandler",
            "level":"ERROR",
            "formatter":"simple",
            "filename":"errors.log",
            "maxBytes":10485760,
            "backupCount":20,
            "encoding":"utf8"
        }
    },
    "loggers":{
        "my_module":{
            "level":"ERROR",
            "handlers":["info_file_handler"],
            "propagate":"no"
        }
    },
    "root":{
        "level":"INFO",
        "handlers":["console","info_file_handler","error_file_handler"]
    }
}

通過JSON加載配置文件,然後通過logging.dictConfig配置logging,

import json
import logging.config
import os

def setup_logging(default_path = "logging.json",default_level = logging.INFO,env_key = "LOG_CFG"):
    path = default_path
    value = os.getenv(env_key,None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path,"r") as f:
            config = json.load(f)
            logging.config.dictConfig(config)
    else:
        logging.basicConfig(level = default_level)

def func():
    logging.info("start func")

    logging.info("exec func")

    logging.info("end func")

if __name__ == "__main__":
    setup_logging(default_path = "logging.json")
    func()

3.2 通過YAML文件配置

通過YAML文件進行配置,比JSON看起來更加簡介明了,

version: 1
disable_existing_loggers: False
formatters:
        simple:
            format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
    console:
            class: logging.StreamHandler
            level: DEBUG
            formatter: simple
            stream: ext://sys.stdout
    info_file_handler:
            class: logging.handlers.RotatingFileHandler
            level: INFO
            formatter: simple
            filename: info.log
            maxBytes: 10485760
            backupCount: 20
            encoding: utf8
    error_file_handler:
            class: logging.handlers.RotatingFileHandler
            level: ERROR
            formatter: simple
            filename: errors.log
            maxBytes: 10485760
            backupCount: 20
            encoding: utf8
loggers:
    my_module:
            level: ERROR
            handlers: [info_file_handler]
            propagate: no
root:
    level: INFO
    handlers: [console,info_file_handler,error_file_handler]

通過YAML加載配置文件,然後通過logging.dictConfig配置logging,

import yaml
import logging.config
import os

def setup_logging(default_path = "logging.yaml",default_level = logging.INFO,env_key = "LOG_CFG"):
    path = default_path
    value = os.getenv(env_key,None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path,"r") as f:
            config = yaml.load(f)
            logging.config.dictConfig(config)
    else:
        logging.basicConfig(level = default_level)

def func():
    logging.info("start func")

    logging.info("exec func")

    logging.info("end func")

if __name__ == "__main__":
    setup_logging(default_path = "logging.yaml")
    func()
    

4 Reference

每個 Python 程序員都要知道的日誌實踐

Python標準模塊logging

python 的日誌logging模塊學習

Python模塊學習--logging