歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python模塊之logging

Python模塊之logging

日期:2017/3/1 9:14:49   编辑:Linux編程

前言

Python 的logging 模塊定義的函數和類為應用程序和庫實現了一個靈活的事件日志系統。該模塊提供多種日志級別並且支持多種記錄日志的方式比如 終端,文件等等。在編寫一個軟件系統的時候 ,使用日志系統十分有必要 記錄函數的執行過程和異常報錯信息。本文算是一個學習筆記,對於跨文件引用的初學者有一定幫助。 一 入門 talk is cheap ,show me the code. 1 例子 logt.py
  1. #!/usr/bin/python
  2. # -*- coding:utf-8 -*-
  3. import logging
  4. logging.debug('this is a debug message')
  5. logging.info('this is a info message')
  6. logging.warn('this is a warn message')
  7. logging.error('this is a error message')
  8. logging.critical('this is a critical message')
運行該腳本
  1. root@rac4:~# >python logt.py
  2. WARNING:root:this is a warn message
  3. ERROR:root:this is a error message
  4. CRITICAL:root:this is a critical message
看到這個輸出 ,有人可能會有疑問 為什麼 logging.debug()和logging.info()沒有輸出內容? 恩,這個是個好問題,莫慌,且看下文分析。 2. logging 的日志級別 logging 提供了完整的日志體系,支持五種日志級別以便記錄程序的執行過程。 DEBUG 詳細信息,典型地調試問題的時候會使用。 INFO 證明事情按預期工作。 WARNING 表明發生了一些意外,或者不久的將來會發生問題(如‘磁盤滿了’)。軟件還是在正常工作。 ERROR 由於更嚴重的問題,軟件已不能執行一些功能了。 CRITICAL 嚴重錯誤,表明軟件已不能繼續運行了。
以上五種日志級別從低到高分別是:DEBUG < INFO < WARNING < ERROR < CRITICAL 。默認的是WARNING,只有日志級別高於WARNING的日志信息才會輸出,而輸出有兩種方式 一種輸出控制台,也是默認的方式,另一種是記錄到文件中,如日志文件。 3 logging的配置 python提供了多種配置方式控制日志的顯示格式,內容,目的等。如上述例子中的日志輸出“WARNING:root:this is awarn message”。 顯式創建記錄器Logger、處理器Handler和格式化器Formatter,並進行相關設置; 通過簡單方式進行配置,使用basicConfig()函數直接進行配置; 通過配置文件進行配置,使用fileConfig()函數讀取配置文件; 通過配置字典進行配置,使用dictConfig()函數讀取配置信息; 本文使用basicConfig()方式作為例子。 basicConfig()支持下列關鍵字參數。 格式 描述 filename 創建一個FileHandler,使用指定的文件名,而不是使用StreamHandler。 filemode 如果指明了文件名,指明打開文件的模式(如果沒有指明filemode,默認為'a',即append方式)。 format handler使用指明的格式化字符串。詳細的請參考 官方文檔 datefmt 使用指明的日期/時間格式 比如 '%Y-%m-%d %H:%M:%S' 2016-06-14 10:10:00。 level 指定logger的日志級別。 stream 使用指明的流來初始化StreamHandler。該參數與'filename'不兼容,如果兩個都有,'stream'將被忽略。
  1. #!/usr/bin/python
  2. # -*- coding:utf-8 -*-
  3. import logging
  4. logging.basicConfig(level=logging.DEBUG,
  5. format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  6. datefmt='%Y%m%d %H:%M:%S',
  7. filename='myapp.log',
  8. filemode='w')
  9. logging.info('info message')
  10. logging.warn('warn message')
  11. logging.error('error message')
  12. logging.critical('critical message')
二 進階介紹 logging模塊提供四個組件logger,handler,filter,formatter logger:記錄器,為應用代碼提供日志接口。logger最長用的操作有兩類:配置和發送日志消息。可以通過logging.getLogger(name 獲取logger對象,如果不指定name則返回root對象,如第一個例子。多次使用相同的name調用getLogger方法返回同一個logger對象。 調用方法:
  1. logger = logging.getLogger(logger_name) #如果不指定 logger_name ,則默認創建一個root logger,見第一個例子。
  2. logger.setLevel(logging.ERROR) #設置日志級別為ERROR,即只有日志級別大於等於ERROR的日志才會輸出
  3. logger.addHandler(handler_name) #為logger實例增加一個處理器
  4. logger.removeHandler(handler_name) # 為logger實例刪除一個處理器
handler:將日志內容發送到合適的目的,比如文件,終端等。一個logger對象可以通過addHandler方法添加0到多個handler,每個handler又可以定義不同日志級別,以實現日志分級過濾顯示。 詳細信息請移步 官方文檔 調用方法
  1. StreamHandler
  2. ch = logging.StreamHandler(stream=None)
  3. FileHandler
  4. fh = logging.FileHandler(filename, mode='a', encoding=None, delay=False)
返回FileHandler類的實例。指明的文件會被打開,並用作日志流。如果沒有指明mode,使用'a'。如果encoding不為None,會用指定的編碼來打開文件。如果delay為真,只到第一次調用emit()的時候才打開文件。默認情況下,文件會一直增長。
filter:提供一種優雅的方式決定一個日志記錄是否發送到handler。
formatter:指定日志記錄輸出的具體格式。formatter的構造方法需要兩個參數:消息的格式字符串和日期字符串,這兩個參數都是可選的。
現在我們測試另外一個例子 test_log.py ,該腳本定義了一個init_log 函數,通過傳入的參數顯示的配置logging。函數裡面創建兩個logging 實例,分別將日志輸出到文件和終端。
  1. import logging
  2. import logging.handlers
  3. LOG_LEVELS = {'DEBUG': logging.DEBUG,
  4. 'INFO': logging.INFO,
  5. 'ERROR': logging.ERROR,
  6. 'CRITICAL': logging.CRITICAL }
  7. LOGGING_FORMAT = "%(asctime)s - [%(name)s] - [%(levelname)s] - %(message)s" #日志的輸出的格式
  8. STANDARD_DATE_FORMAT = '%Y-%m-%d %H:%M:%S' #時間格式 2016-06-14 10:10:00
  9. DEFAULT_LOG_MAX_SIZE = 50 * 1024 * 1024 #當達到50M就進行切分
  10. def init_log(logger_name, level='DEBUG', logfile='/tmp/logtest.log',
  11. formatter=LOGGING_FORMAT, max_size=DEFAULT_LOG_MAX_SIZE):
  12. logger = logging.getLogger('') #初始化一個logging 實例
  13. logger.setLevel(LOG_LEVELS[level]) #設置日志的級別
  14. fh = logging.handlers.RotatingFileHandler(logfile, maxBytes=max_size,backupCount=3)
  15. #定義日志輸出到文件的handler ,也可以定義 fh=logging.FileHandler(logfile)
  16. fh.setLevel(logging.DEBUG)
  17. # create console handler with a higher log level
  18. ch = logging.StreamHandler() #定義日志輸出到終端的handler
  19. ch.setLevel(logging.INFO)
  20. formatter = logging.Formatter(formatter)
  21. fh.setFormatter(formatter)
  22. ch.setFormatter(formatter)
  23. # add the handlers to the logger
  24. logger.addHandler(fh)
  25. logger.addHandler(ch)
  26. return logging.getLogger(logger_name)
  27. if __name__ == '__main__':
  28. LOGGER=init_log('youzan','INFO','0614.log')
  29. LOGGER.info('info message')
  30. LOGGER.warn('warn message')
  31. LOGGER.error('error message')
  32. LOGGER.critical('critical message')
執行該腳本
  1. root@rac4:~# >python logconfig.py
  2. 2016-06-14 10:38:15,190 - [youzan] - [INFO] - info message
  3. 2016-06-14 10:38:15,190 - [youzan] - [WARNING] - warn message
  4. 2016-06-14 10:38:15,191 - [youzan] - [ERROR] - error message
  5. 2016-06-14 10:38:15,191 - [youzan] - [CRITICAL] - critical message
  6. 同時在 0614log 文件裡面也會記錄對應的log
  7. root@rac4:~# >cat 0614.log
  8. 2016-06-14 10:38:15,190 - [youzan] - [INFO] - info message
  9. 2016-06-14 10:38:15,190 - [youzan] - [WARNING] - warn message
  10. 2016-06-14 10:38:15,191 - [youzan] - [ERROR] - error message
  11. 2016-06-14 10:38:15,191 - [youzan] - [CRITICAL] - critical message
三 拓展 其實這才是本章的重點,在構建一個整套的程序時,怎麼全局配置logging 模塊,並在不同的程序中調用呢?例子如下: root@rac4:~/python# >tree . . ├── log2.py — 引用 logconfig中的logging 配置 ├── logconfig.py —配置logging 輸出格式 特別注意,如果是跨文件訪問定義的logconfig 配置 ,必須在 logconfig.py 所在的目錄創建 __init__.py 文件。 log2.py
  1. import sys
  2. import os
  3. sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
  4. import logging
  5. from logconfig import init_log
  6. logger=init_log('logtest','INFO',log='666.log') ##通過傳參來定義新的 logging 模塊配置。
  7. logger.info('this is a test %s'," [email protected]")
  8. logger.debug('debug message')
  9. logger.warn('warn message')
  10. logger.error('error message')
  11. logger.critical('critical message')
  1. root@rac4:~# >python log2.py
  2. 2016-06-14 13:26:50,713 - [logtest] - [INFO] - this is a test [email protected]
  3. 2016-06-14 13:26:50,713 - [logtest] - [WARNING] - warn message
  4. 2016-06-14 13:26:50,714 - [logtest] - [ERROR] - error message
  5. 2016-06-14 13:26:50,714 - [logtest] - [CRITICAL] - critical message

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved