日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python配置日志的几种方式

發布時間:2024/10/12 python 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python配置日志的几种方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

使用的是logging模塊,關于logging模塊內容,可以看我的另一篇博客:https://www.cnblogs.com/kuxingseng95/p/9464347.html

作為開發者,我們一般使用三種方式來配置logging:

  • 使用Python代碼顯式的創建loggers, handlers和formatters并分別調用它們的配置函數;
  • 創建一個日志配置文件,然后使用fileConfig()函數來讀取該文件的內容;
  • 創建一個包含配置信息的dict,然后把它傳遞個dictConfig()函數;

需要說明的是,logging.basicConfig()也屬于第一種方式,它只是對loggers, handlers和formatters的配置函數進行了封裝。另外,第二種配置方式相對于第一種配置方式的優點在于,它將配置信息和代碼進行了分離,這一方面降低了日志的維護成本,同時還使得非開發人員也能夠去很容易地修改日志配置。

使用python代碼實現日志配置

import logging import sys # 創建一個日志器logger并設置其日志級別為DEBUG logger = logging.getLogger('simple_logger') logger.setLevel(logging.DEBUG)# 創建一個流處理器handler并設置其日志級別為DEBUG handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG)# 創建一個格式器formatter并將其添加到處理器handler formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter)# 為日志器logger添加上面創建的處理器handler logger.addHandler(handler)# 日志輸出 logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')# 運行結果 # 2018-08-15 08:43:57,794 - simple_logger - DEBUG - debug message # 2018-08-15 08:43:57,794 - simple_logger - INFO - info message # 2018-08-15 08:43:57,796 - simple_logger - WARNING - warn message # 2018-08-15 08:43:57,796 - simple_logger - ERROR - error message # 2018-08-15 08:43:57,796 - simple_logger - CRITICAL - critical message

使用配置文件配置日志

python代碼中

import logging.config# 讀取日志配置文件內容 logging.config.fileConfig('logging.conf')# 創建一個日志器logger logger = logging.getLogger('simpleExample')# 日志輸出 logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')

創建配置文件:logging.conf:

[loggers] keys=root,simpleExample[handlers] keys=fileHandler,consoleHandler[formatters] keys=simpleFormatter[logger_root] level=DEBUG handlers=fileHandler[logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0[handler_consoleHandler] class=StreamHandler args=(sys.stdout,) level=DEBUG formatter=simpleFormatter[handler_fileHandler] class=FileHandler args=('logging.log', 'a') level=ERROR formatter=simpleFormatter[formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt=

輸出為:

2018-08-15 08:48:31,516 - simpleExample - DEBUG - debug message 2018-08-15 08:48:31,516 - simpleExample - INFO - info message 2018-08-15 08:48:31,516 - simpleExample - WARNING - warn message 2018-08-15 08:48:31,516 - simpleExample - ERROR - error message 2018-08-15 08:48:31,516 - simpleExample - CRITICAL - critical message

說明

該函數實際上是對configparser模塊的封裝,關于configparser模塊的介紹請參考<。

函數定義

該函數定義在loging.config模塊下:

logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True)

參數:

  • fname:表示配置文件的文件名或文件對象
  • defaults:指定傳給ConfigParser的默認值
  • disable_existing_loggers:這是一個布爾型值,默認值為True(為了向后兼容)表示禁用已經存在的logger,除非它們或者它們的祖先明確的出現在日志配置中;如果值為False則對已存在的loggers保持啟動狀態。

配置文件格式說明

上面提到過,fileConfig()函數是對ConfigParser/configparser模塊的封裝,也就是說fileConfig()函數是基于ConfigParser/configparser模塊來理解日志配置文件的。換句話說,fileConfig()函數所能理解的配置文件基礎格式是與ConfigParser/configparser模塊一致的,只是在此基礎上對文件中包含的section和option做了一下規定和限制,比如:

  • 1)配置文件中一定要包含loggers、handlers、formatters這些section,它們通過keys這個option來指定該配置文件中已經定義好的loggers、handlers和formatters,多個值之間用逗號分隔;另外loggers這個section中的keys一定要包含root這個值;

  • 2)loggers、handlers、formatters中所指定的日志器、處理器和格式器都需要在下面以單獨的section進行定義。seciton的命名規則為[logger_loggerName]、[formatter_formatterName]、[handler_handlerName]

  • 3)定義logger的section必須指定level和handlers這兩個option,level的可取值為DEBUG、INFO、WARNING、ERROR、CRITICAL、NOTSET,其中NOTSET表示所有級別的日志消息都要記錄,包括用戶定義級別;handlers的值是以逗號分隔的handler名字列表,這里出現的handler必須出現在[handlers]這個section中,并且相應的handler必須在配置文件中有對應的section定義;

  • 4)對于非root logger來說,除了level和handlers這兩個option之外,還需要一些額外的option,其中qualname是必須提供的option,它表示在logger層級中的名字,在應用代碼中通過這個名字得到logger;propagate是可選項,其默認是為1,表示消息將會傳遞給高層次logger的handler,通常我們需要指定其值為0,這個可以看下下面的例子;另外,對于非root logger的level如果設置為NOTSET,系統將會查找高層次的logger來決定此logger的有效level。

  • 5)定義handler的section中必須指定class和args這兩個option,level和formatter為可選option;class表示用于創建handler的類名,args表示傳遞給class所指定的handler類初始化方法參數
    ,它必須是一個元組(tuple)的形式,即便只有一個參數值也需要是一個元組的形式;level與logger中的level一樣,而formatter指定的是該處理器所使用的格式器,這里指定的格式器名稱必須出現在formatters這個section中,且在配置文件中必須要有這個formatter的section定義;如果不指定formatter則該handler將會以消息本身作為日志消息進行記錄,而不添加額外的時間、日志器名稱等信息;

  • 6)定義formatter的sectioin中的option都是可選的,其中包括format用于指定格式字符串,默認為消息字符串本身;datefmt用于指定asctime的時間格式,默認為'%Y-%m-%d %H:%M:%S';class用于指定格式器類名,默認為logging.Formatter;

說明:

配置文件中的class指定類名時,該類名可以是相對于logging模塊的相對值,如:FileHandler、handlers.TimeRotatingFileHandler;也可以是一個絕對路徑值,通過普通的import機制來解析,如自定義的handler類mypackage.mymodule.MyHandler,但是mypackage需要在Python可用的導入路徑中--sys.path。

對于propagate屬性的說明

實例1:

我們把logging.conf中simpleExample這個handler定義中的propagate屬性值改為1,或者刪除這個option(默認值就是1):

[logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=1

現在來執行同樣的代碼:

# 讀取日志配置文件內容 logging.config.fileConfig('logging.conf')# 創建一個日志器logger logger = logging.getLogger('simpleExample')# 日志輸出 logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')

我們會發現,除了在控制臺有輸出信息時候,在logging.log文件中也有內容輸出:

2018-08-15 09:26:08,922 - simpleExample - ERROR - error message
2018-08-15 09:26:08,922 - simpleExample - CRITICAL - critical message

這說明simpleExample這個logger在處理完日志記錄后,把日志記錄傳遞給了上級的root logger再次做處理,所有才會有兩個地方都有日志記錄的輸出。通常,我們都需要顯示的指定propagate的值為0,防止日志記錄向上層logger傳遞。

實例2:

現在,我們試著用一個沒有在配置文件中定義的logger名稱來獲取logger:

# 讀取日志配置文件內容 logging.config.fileConfig('logging.conf')# 用一個沒有在配置文件中定義的logger名稱來創建一個日志器logger logger = logging.getLogger('simpleExample1')# 日志輸出 logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')

運行程序后,我們會發現控制臺沒有任何輸出,而logging.log文件中又多了兩行輸出:

2018-08-15 09:45:20,066 - simpleExample1 - ERROR - error message 2018-08-15 09:45:20,066 - simpleExample1 - CRITICAL - critical message

這是因為,當一個日志器沒有被設置任何處理器是,系統會去查找該日志器的上層日志器上所設置的日志處理器來處理日志記錄。simpleExample1在配置文件中沒有被定義,因此logging.getLogger(simpleExample1)這行代碼這是獲取了一個logger實例,并沒有給它設置任何處理器,但是它的上級日志器--root logger在配置文件中有定義且設置了一個FileHandler處理器,simpleExample1處理器最終通過這個FileHandler處理器將日志記錄輸出到logging.log文件中了。

使用字典配置日志信息

Python 3.2中引入的一種新的配置日志記錄的方法--用字典來保存logging配置信息。這相對于上面所講的基于配置文件來保存logging配置信息的方式來說,功能更加強大,也更加靈活,因為我們可把很多的數據轉換成字典。比如,我們可以使用JSON格式的配置文件、YAML格式的配置文件,然后將它們填充到一個配置字典中;或者,我們也可以用Python代碼構建這個配置字典,或者通過socket接收pickled序列化后的配置信息。總之,你可以使用你的應用程序可以操作的任何方法來構建這個配置字典。

實際中經常用json和yaml配置,所以我寫了一個簡單的函數,用來啟動日志記錄:

import logging.config import json import os import yamldef setup_logging(default_path="logging.json", default_level=logging.INFO, env_key="LOG_CFG"):path = default_pathvalue = os.getenv(env_key, None)if value:path = valueif os.path.exists(path) and os.path.splitext(path)[1] == ".json":with open(path, 'r') as f_conf:dict_conf = json.load(f_conf)logging.config.dictConfig(dict_conf)elif os.path.exists(path) and os.path.splitext(path)[1] == ".yaml":with open(path, 'r') as f_conf:dict_conf = yaml.load(f_conf)logging.config.dictConfig(dict_conf)else:logging.basicConfig(level=default_level)

通過json文件配置

創建json配置文件logging.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": ["console"],"propagate": "yes"}},"root": {"level": "INFO","handlers": ["console", "info_file_handler", "error_file_handler"]} }

使用上面自定義的函數:

if __name__ == "__main__":setup_logging(default_path="logging.json")logging.debug('debug message')logging.info('info message')logging.warn('warn message')logging.error('error message')logging.critical('critical message')

通過yaml文件配置

使用yaml文件配置首先要安裝PyYAML模塊

pip install PyYAML

創建yaml配置文件logging.yaml:

version: 1disable_existing_loggers: Falseformatters:simple:format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"handlers:console:class: logging.StreamHandlerlevel: DEBUGformatter: simplestream: ext://sys.stdoutinfo_file_handler:class: logging.handlers.RotatingFileHandlerlevel: INFOformatter: simplefilename: info.logmaxBytes: 10485760 # 10MBbackupCount: 20encoding: utf8error_file_handler:class: logging.handlers.RotatingFileHandlerlevel: ERRORformatter: simplefilename: errors.logmaxBytes: 10485760 # 10MBbackupCount: 20encoding: utf8loggers:my_module:level: ERRORhandlers: [console]propagate: noroot:level: INFOhandlers: [console, info_file_handler, error_file_handler]

使用上面自定義的函數:

if __name__ == "__main__":setup_logging(default_path="logging.yaml")logging.debug('debug message')logging.info('info message')logging.warn('warn message')logging.error('error message')logging.critical('critical message')

說明

關于json和yaml

使用json的好處就是json是一個標準庫,不需要額外安裝,使用yaml的好處就是好讀好寫。

關于dicConfig()函數的說明

該函數實際上是對configparser模塊的封裝,關于configparser模塊的介紹請參考<。

函數定義:

該函數定義在loging.config模塊下:

logging.config.dictConfig(config)

該函數可以從一個字典對象中獲取日志配置信息,config參數就是這個字典對象。關于這個字典對象的內容規則會在下面進行描述。

配置說明

無論是上面提到的配置文件,還是這里的配置字典,它們都要描述出日志配置所需要創建的各種對象以及這些對象之間的關聯關系。比如,可以先創建一個名額為“simple”的格式器formatter;然后創建一個名為“console”的處理器handler,并指定該handler輸出日志所使用的格式器為"simple";然后再創建一個日志器logger,并指定它所使用的處理器為"console"。

傳遞給dictConfig()函數的字典對象只能包含下面這些keys,其中version是必須指定的key,其它key都是可選項:

比如handlers的定義示例:

handlers:console:class : logging.StreamHandlerformatter: brieflevel : INFOfilters: [allow_foo]stream : ext://sys.stdoutfile:class : logging.handlers.RotatingFileHandlerformatter: precisefilename: logconfig.logmaxBytes: 1024backupCount: 3

?關于外部對象的訪問

需要說明的是,上面所使用的對象并不限于loggging模塊所提供的對象,我們可以實現自己的formatter或handler類。另外,這些類的參數也許需要包含sys.stderr這樣的外部對象。如果配置字典對象是使用Python代碼構造的,可以直接使用sys.stdout、sys.stderr;但是當通過文本文件(如JSON、YAML格式的配置文件)提供配置時就會出現問題,因為在文本文件中,沒有標準的方法來區分sys.stderr和字符串'sys.stderr'。為了區分它們,配置系統會在字符串值中查找特定的前綴,例如'ext://sys.stderr'中'ext://'會被移除,然后import sys.stderr。

  • 參考文檔:https://docs.python.org/3.5/library/logging.config.html

【轉】 向日志輸出中添加上下文信息:http://www.cnblogs.com/yyds/p/6897964.html

轉載于:https://www.cnblogs.com/kuxingseng95/p/9480555.html

總結

以上是生活随笔為你收集整理的python配置日志的几种方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。