我們可以通過以下3種方式可以很優雅配置logging日志:
- 1)使用Python代碼顯式的創建loggers, handlers和formatters並分別調用它們的配置函數;
- 2)創建一個日志配置文件,然后使用
fileConfig()
函數來讀取該文件的內容; - 3)創建一個包含配置信息的dict,然后把它傳遞個
dictConfig()
函數;
需要說明的是,logging.basicConfig()
也屬於第一種方式,它只是對loggers, handlers和formatters的配置函數進行了封裝。另外,第二種配置方式相對於第一種配置方式的優點在於,它將配置信息和代碼進行了分離,這一方面降低了日志的維護成本,同時還使得非開發人員也能夠去很容易地修改日志配置。
一、使用Python代碼實現日志配置
代碼如下:
# 創建一個日志器logger並設置其日志級別為DEBUG logger = logging.getLogger('simple_logger') logger.setLevel(logging.DEBUG) logging.basicConfig(filename="app.log",level=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')
運行輸出:
2017-05-15 11:30:50,955 - simple_logger - DEBUG - debug message 2017-05-15 11:30:50,955 - simple_logger - INFO - info message 2017-05-15 11:30:50,955 - simple_logger - WARNING - warn message 2017-05-15 11:30:50,955 - simple_logger - ERROR - error message 2017-05-15 11:30:50,955 - simple_logger - CRITICAL - critical message
二、使用配置文件和fileConfig()函數實現日志配置
現在我們通過配置文件的方式來實現與上面同樣的功能:
# 讀取日志配置文件內容 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=
運行輸出:
2017-05-15 11:32:16,539 - simpleExample - DEBUG - debug message 2017-05-15 11:32:16,555 - simpleExample - INFO - info message 2017-05-15 11:32:16,555 - simpleExample - WARNING - warn message 2017-05-15 11:32:16,555 - simpleExample - ERROR - error message 2017-05-15 11:32:16,555 - simpleExample - CRITICAL - critical message
1. 關於fileConfig()
函數的說明:
該函數實際上是對configparser
模塊的封裝,關於configparser
模塊的介紹請參考<。
函數定義:
該函數定義在loging.config模塊下:
logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True)
參數:
- fname:表示配置文件的文件名或文件對象
- defaults:指定傳給ConfigParser的默認值
- disable_existing_loggers:這是一個布爾型值,默認值為True(為了向后兼容)表示禁用已經存在的logger,除非它們或者它們的祖先明確的出現在日志配置中;如果值為False則對已存在的loggers保持啟動狀態。
2. 配置文件格式說明:
上面提到過,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。
3. 對於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文件中也有內容輸出:
2017-05-15 16:06:25,366 - simpleExample - ERROR - error message 2017-05-15 16:06:25,367 - 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文件中又多了兩行輸出:
2017-05-15 16:13:16,810 - simpleExample1 - ERROR - error message 2017-05-15 16:13:16,810 - simpleExample1 - CRITICAL - critical message
這是因為,當一個日志器沒有被設置任何處理器是,系統會去查找該日志器的上層日志器上所設置的日志處理器來處理日志記錄。simpleExample1在配置文件中沒有被定義,因此logging.getLogger(simpleExample1)
這行代碼這是獲取了一個logger實例,並沒有給它設置任何處理器,但是它的上級日志器--root logger在配置文件中有定義且設置了一個FileHandler處理器,simpleExample1處理器最終通過這個FileHandler處理器將日志記錄輸出到logging.log文件中了。
三、使用字典配置信息和dictConfig()函數實現日志配置
Python 3.2中引入的一種新的配置日志記錄的方法--用字典來保存logging配置信息。這相對於上面所講的基於配置文件來保存logging配置信息的方式來說,功能更加強大,也更加靈活,因為我們可把很多的數據轉換成字典。比如,我們可以使用JSON格式的配置文件、YAML格式的配置文件,然后將它們填充到一個配置字典中;或者,我們也可以用Python代碼構建這個配置字典,或者通過socket接收pickled序列化后的配置信息。總之,你可以使用你的應用程序可以操作的任何方法來構建這個配置字典。
這個例子中,我們將使用YAML格式來完成與上面同樣的日志配置。
首先需要安裝PyYAML模塊:
pip install PyYAML
Python代碼:
import logging
import logging.config import yaml with open('logging.yml', 'r') as f_conf: dict_conf = yaml.load(f_conf) logging.config.dictConfig(dict_conf) 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.yml配置文件的內容:
version: 1 formatters: simple: format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' handlers: console: class: logging.StreamHandler level: DEBUG formatter: simple stream: ext://sys.stdout console_err: class: logging.StreamHandler level: ERROR formatter: simple stream: ext://sys.stderr loggers: simpleExample: level: DEBUG handlers: [console] propagate: yes root: level: DEBUG handlers: [console_err]
輸出結果:
2017-05-21 14:19:31,089 - simpleExample - DEBUG - debug message 2017-05-21 14:19:31,089 - simpleExample - INFO - info message 2017-05-21 14:19:31,089 - simpleExample - WARNING - warn message 2017-05-21 14:19:31,089 - simpleExample - ERROR - error message 2017-05-21 14:19:31,090 - simpleExample - CRITICAL - critical message
1. 關於dictConfig()
函數的說明:
該函數實際上是對configparser
模塊的封裝,關於configparser
模塊的介紹請參考<。
函數定義:
該函數定義在loging.config模塊下:
logging.config.dictConfig(config)
該函數可以從一個字典對象中獲取日志配置信息,config參數就是這個字典對象。關於這個字典對象的內容規則會在下面進行描述。
2. 配置字典說明
無論是上面提到的配置文件,還是這里的配置字典,它們都要描述出日志配置所需要創建的各種對象以及這些對象之間的關聯關系。比如,可以先創建一個名額為“simple”的格式器formatter;然后創建一個名為“console”的處理器handler,並指定該handler輸出日志所使用的格式器為"simple";然后再創建一個日志器logger,並指定它所使用的處理器為"console"。
傳遞給dictConfig()函數的字典對象只能包含下面這些keys,其中version
是必須指定的key,其它key都是可選項:
key名稱 | 描述 |
---|---|
version | 必選項,其值是一個整數值,表示配置格式的版本,當前唯一可用的值就是1 |
formatters | 可選項,其值是一個字典對象,該字典對象每個元素的key為要定義的格式器名稱,value為格式器的配置信息組成的dict,如format和datefmt |
filters | 可選項,其值是一個字典對象,該字典對象每個元素的key為要定義的過濾器名稱,value為過濾器的配置信息組成的dict,如name |
handlers | 可選項,其值是一個字典對象,該字典對象每個元素的key為要定義的處理器名稱,value為處理器的配置信息組成的dcit,如class、level、formatter和filters,其中class為必選項,其它為可選項;其他配置信息將會傳遞給class所指定的處理器類的構造函數,如下面的handlers定義示例中的stream、filename、maxBytes和backupCount等 |
loggers | 可選項,其值是一個字典對象,該字典對象每個元素的key為要定義的日志器名稱,value為日志器的配置信息組成的dcit,如level、handlers、filters 和 propagate(yes |
root | 可選項,這是root logger的配置信息,其值也是一個字典對象。除非在定義其它logger時明確指定propagate值為no,否則root logger定義的handlers都會被作用到其它logger上 |
incremental | 可選項,默認值為False。該選項的意義在於,如果這里定義的對象已經存在,那么這里對這些對象的定義是否應用到已存在的對象上。值為False表示,已存在的對象將會被重新定義。 |
disable_existing_loggers | 可選項,默認值為True。該選項用於指定是否禁用已存在的日志器loggers,如果incremental的值為True則該選項將會被忽略 |
handlers定義示例:
handlers: console: class : logging.StreamHandler formatter: brief level : INFO filters: [allow_foo] stream : ext://sys.stdout file: class : logging.handlers.RotatingFileHandler formatter: precise filename: logconfig.log maxBytes: 1024 backupCount: 3
3. 關於外部對象的訪問
需要說明的是,上面所使用的對象並不限於loggging模塊所提供的對象,我們可以實現自己的formatter或handler類。另外,這些類的參數也許需要包含sys.stderr這樣的外部對象。如果配置字典對象是使用Python代碼構造的,可以直接使用sys.stdout、sys.stderr;但是當通過文本文件(如JSON、YAML格式的配置文件)提供配置時就會出現問題,因為在文本文件中,沒有標准的方法來區分sys.stderr
和字符串'sys.stderr'
。為了區分它們,配置系統會在字符串值中查找特定的前綴,例如'ext://sys.stderr'中'ext://'會被移除,然后import sys.stderr
。
logging模塊的四個重點:
logger:日志生產者
handler:日志接收處理者(logger生產日志送給handler)
formatter:日志格式化(在handler接收到日志后需要綁定format日志格式處理)
filter:暫時略過
在日志配置文件如何定義logger,handler,formatter?
loggers:keys關聯多個logger,其中root為必須(loggers與logger)
level:日志級別
handler:處理后輸出位置
qualname:定義logger對象是需要綁定的日志策略名字
progarate:是否將日志傳給上游(多級上游,頂級為root,以foo.A.B類似表示,foo就是A,B的頂級,A就是B的父級)
....
handlers:keys關聯多個定義的handler class:日志輸出位置,StreamHandler,FileHandler,....... level:日志級別 formatter:日志格式 args:日志處理對象的參數,比如StreamHandler輸出參數可以是sys.stdout,必須是元組格式 formatters:關聯多個定義了的formatter format:日志格式 datefmt:時間格式 日志格式定義: %(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: 打印日志信息
配置文件定義:
loggers關聯多個logger,formatters關聯多個formatter,handlers關聯多個handler
logger關聯handler,handler定義輸出與關聯formatter
配置案例:
定義日志策略:
[loggers]
keys=root,l1,l2,l3
[handlers]
keys=h1,h2,h3
[formatters]
keys=f1,f2,f3
[logger_root]
level=NOTSET
handlers=h1
[logger_l1]
level=DEBUG
handlers=h1
qualname=h1
progarate=1 [logger_l2] level=INFO handlers=h2 qualname=h2 progarate=0 [logger_l3] level=ERROR handlers=h3 qualname=h3 progarate=0 [handler_h1] class=StreamHandler level=NOTSET formatter=f1 args=(sys.stdout,) [handler_h2] class=FileHandler level=INFO formatter=f2 args=('l2h2f2.txt','a') [handler_h3] class=FileHandler level=ERROR formatter=f3 args=('l3h3f3.txt','a') [formatter_f1] format='%(levelno)s - %(levelname)s - %(pathname)s - %(filename)s - %(funcName)s - %(lineno)d - %(thread)d - %(threadName)s - %(process)d - %(message)s' [formatter_f2] format='%(levelno)s - %(pathname)s - %(filename)s - %(funcName)s - %(lineno)d - %(thread)d - %(threadName)s - %(process)d - %(message)s' [formatter_f3] format='%(levelno)s - %(filename)s - %(funcName)s - %(lineno)d - %(thread)d - %(threadName)s - %(process)d - %(message)s'
代碼定義日志:
import logging import logging.config logging.config.fileConfig('logging1.ini') # logger1 = logging.getLogger('h1') # logger1.debug('debug message') # logger1.info('info message') # logger1.warning('warning message') # logger1.error('error message') # logger1.critical('critical message') logger2 = logging.getLogger('h2') logger2.debug('debug message') logger2.info('info message') logger2.warning('warning message') logger2.error('error message') logger2.critical('critical message') logger3 = logging.getLogger('h3') logger3.debug('debug message') logger3.info('info message') logger3.warning('warning message') logger3.error('error message') logger3.critical('critical message')
作者:詞窮又詞貧
鏈接:https://www.jianshu.com/p/4f6ff84cb3e9
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。