標籤:view key 官方文檔 gre system for 系統 obb logs
前言
日誌是非常重要的,最近有接觸到這個,所以系統的看一下Python這個模組的用法。本文即為Logging模組的用法簡介,主要參考文章為Python官方文檔,連結見參考列表。
另外,Python的HOWTOs文檔很詳細,連日誌該怎麼用都寫了,所以有英文閱讀能力的同學建議去閱讀一下。
Logging模組構成組成
主要分為四個部分:
- Loggers:提供應用程式直接使用的介面
- Handlers:將Loggers產生的日誌傳到指定位置
- Filters:對輸出日誌進行過濾
- Formatters:控制輸出格式
記錄層級
Level |
Numeric value |
When it’s used |
DEBUG |
10 |
Detailed information, typically of interest only when diagnosing problems. |
INFO |
20 |
Confirmation that things are working as expected. |
WARNING |
30 |
An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
ERROR |
40 |
Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL |
50 |
A serious error, indicating that the program itself may be unable to continue running. |
NOSET |
0 |
getattr(logging, loglevel.upper()) |
預設層級是WARNING,可以使用列印到螢幕上的方式記錄,也可以記錄到檔案中。
模組使用樣本簡單例子列印輸出
In [5]: import loggingIn [6]: logging.warning("FBI warning")WARNING:root:FBI warningIn [7]: logging.info("information")# 沒有列印是因為預設層級是warning
輸出到檔案中
In [4]: import loggingIn [5]: logging.basicConfig(filename=‘example.log‘, level=logging.DEBUG)In [6]: logging.debug("debug")In [7]: logging.warning(‘warning‘)In [8]: logging.info(‘info‘)In [9]: lsC++ STL/ a.py example.log parser/ test.sh*In [10]: cat example.logDEBUG:root:debugWARNING:root:warningINFO:root:infoIn [14]: logging.warning(‘new warning‘)# 注意這種是直接往後面添加,也就是add的,若是想覆蓋內容可以變更檔寫入方式In [15]: cat example.logDEBUG:root:debugWARNING:root:warningINFO:root:infoWARNING:root:new warning# 覆蓋的方式寫入例子(test) ? test ipythonWARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.Python 2.7.11 (default, Jun 17 2016, 20:01:51)Type "copyright", "credits" or "license" for more information.IPython 4.2.0 -- An enhanced Interactive Python.? -> Introduction and overview of IPython‘s features.%quickref -> Quick reference.help -> Python‘s own help system.object? -> Details about ‘object‘, use ‘object??‘ for extra details.In [1]: import loggingIn [2]: logging.basicConfig(filename=‘example.log‘, filemode=‘w‘, level=logging.DEBUG)In [3]: logging.warning(‘FBI warning‘)In [4]: lsC++ STL/ a.py example.log parser/ test.sh*In [5]: cat example.logWARNING:root:FBI warningIn [6]: quit(test) ? test ipythonWARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.Python 2.7.11 (default, Jun 17 2016, 20:01:51)Type "copyright", "credits" or "license" for more information.IPython 4.2.0 -- An enhanced Interactive Python.? -> Introduction and overview of IPython‘s features.%quickref -> Quick reference.help -> Python‘s own help system.object? -> Details about ‘object‘, use ‘object??‘ for extra details.In [1]: import loggingIn [2]: logging.basicConfig(filename=‘example.log‘, filemode=‘w‘, level=logging.DEBUG)In [3]: logging.warning(‘warning‘)In [4]: cat example.logWARNING:root:warning
變數的使用
和print
語句中使用變數一樣,如:
In [5]: logging.warning(‘%s before you %s‘, ‘Look‘, ‘leap!‘)In [6]: cat example.logWARNING:root:warningWARNING:root:Look before you leap!
輸出格式
可以在basicConfig
中設定,參數名稱可以參見連結,可以設定時間什麼的,如:
In [2]: import loggingIn [3]: logging.basicConfig(format=‘%(asctime)s:%(levelname)s:%(message)s‘, level=logging.DEBUG)In [4]: logging.warning(‘And this, too‘)2016-12-06 15:40:43,577:WARNING:And this, too
進階使用
當想項目中使用logging模組的時候肯定不能在這樣一句句的寫了,一般可能會抽象出一個模組來,這樣比較有效一些。logging模組提供了四個類(Loggers,Formatters,Filtters,Handlers)來實現不同的功能,與此對應的我們如果想封裝一個函數,也就要針對這幾個功能來自訂一下。
想自訂的話思路也很簡單,首先執行個體化一個相應的對象,然後進行一些設定,可以簡單看一下下面的例子:
import logging# create loggerlogger = logging.getLogger(‘simple_example‘)logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()ch.setLevel(logging.DEBUG)# create formatterformatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)# add formatter to chch.setFormatter(formatter)# add ch to loggerlogger.addHandler(ch)# ‘application‘ codelogger.debug(‘debug message‘)logger.info(‘info message‘)logger.warn(‘warn message‘)logger.error(‘error message‘)logger.critical(‘critical message‘)# 輸出是:$ python simple_logging_module.py2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message2005-03-19 15:10:26,620 - simple_example - INFO - info message2005-03-19 15:10:26,695 - simple_example - WARNING - warn message2005-03-19 15:10:26,697 - simple_example - ERROR - error message2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
從設定檔匯入配置
模組內容:
import loggingimport logging.configlogging.config.fileConfig(‘logging.conf‘)# create loggerlogger = logging.getLogger(‘simpleExample‘)# ‘application‘ codelogger.debug(‘debug message‘)logger.info(‘info message‘)logger.warn(‘warn message‘)logger.error(‘error message‘)logger.critical(‘critical message‘)# 輸出$ python simple_logging_config.py2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message2005-03-19 15:38:55,979 - simpleExample - INFO - info message2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message2005-03-19 15:38:56,055 - simpleExample - ERROR - error message2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
設定檔內容:
[loggers]keys=root,simpleExample[handlers]keys=consoleHandler[formatters]keys=simpleFormatter[logger_root]level=DEBUGhandlers=consoleHandler[logger_simpleExample]level=DEBUGhandlers=consoleHandlerqualname=simpleExamplepropagate=0[handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,)[formatter_simpleFormatter]format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
同時也可以使用YAML格式的設定檔,如:
version: 1formatters: simple: format: ‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘handlers: console: class: logging.StreamHandler level: DEBUG formatter: simple stream: ext://sys.stdoutloggers: simpleExample: level: DEBUG handlers: [console] propagate: noroot: level: DEBUG handlers: [console]
PS
Logging模組使用也會有很多坑,常見的是日誌重複列印的問題,大家可以搜一下,這裡提供一些連結供參考:
- http://www.jianshu.com/p/25f70905ae9d
- https://yinzo.github.io/14610807170718.html
- http://python.jobbole.com/86887/
參考
- https://docs.python.org/2/library/logging.html
- https://docs.python.org/2/howto/logging.html#logging-basic-tutorial
轉自http://www.cnblogs.com/wswang/p/6138304.html
python logging模組學習(轉)