您好,登錄后才能下訂單哦!
Python 中的 logging 模塊可以讓你跟蹤代碼運行時的事件,當程序崩潰時可以查看日志并且發現是什么引發了錯誤。Log 信息有內置的層級——調試(debugging)、信息(informational)、警告(warnings)、錯誤(error)和嚴重錯誤(critical)。你也可以在 logging 中包含 traceback 信息。不管是小項目還是大項目,都推薦在 Python 程序中使用 logging。本文給大家介紹python 日志 logging模塊 介紹。
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.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 將日志同時輸出到屏幕和日志文件
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.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()
到此這篇關于python 日志 logging模塊 詳細解析的文章就介紹到這了,更多相關python logging模塊內容請搜索億速云以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持億速云!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。