logging模塊簡(jiǎn)介
logging模塊是Python內(nèi)置的標(biāo)準(zhǔn)模塊食听,主要用于輸出運(yùn)行日志娘纷,可以設(shè)置輸出日志的等級(jí)植阴、日志保存路徑酷愧、日志文件回滾等烈拒;相比print滓侍,具備如下優(yōu)點(diǎn):
- 可以通過設(shè)置不同的日志等級(jí)绍傲,在release版本中只輸出重要信息憾儒,而不必顯示大量的調(diào)試信息
- print將所有信息都輸出到標(biāo)準(zhǔn)輸出中规哲,嚴(yán)重影響開發(fā)者從標(biāo)準(zhǔn)輸出中查看其它數(shù)據(jù)跟啤;logging則可以由開發(fā)者決定將信息輸出到什么地方,以及怎么輸出媳叨;
logging模塊使用
1. 基本使用
配置logging基本的設(shè)置腥光,然后在控制臺(tái)輸出日志,
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")
運(yùn)行輸出
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中可以選擇很多消息級(jí)別糊秆,如debug武福、info、warning痘番、error以及critical捉片。通過賦予logger或者h(yuǎn)andler不同的級(jí)別,開發(fā)者就可以只輸出錯(cuò)誤信息到特定的記錄文件汞舱,或者在調(diào)試時(shí)只記錄調(diào)試信息伍纫。
例如,我們將logger的級(jí)別改為DEBUG昂芜,再觀察一下輸出結(jié)果莹规,
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
從輸出可以看出,多了debug級(jí)別的消息
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函數(shù)各參數(shù):
- filename:指定日志文件名泌神;
- filemode:和file函數(shù)意義相同良漱,指定日志文件的打開模式舞虱,'w'或者'a';
- format:指定輸出的格式和內(nèi)容母市,format可以輸出很多有用的信息矾兜,
format 參數(shù)
%(levelno)s:打印日志級(jí)別的數(shù)值
%(levelname)s:打印日志級(jí)別的名稱
%(pathname)s:打印當(dāng)前執(zhí)行程序的路徑,其實(shí)就是sys.argv[0]
%(filename)s:打印當(dāng)前執(zhí)行程序名
%(funcName)s:打印日志的當(dāng)前函數(shù)
%(lineno)d:打印日志的當(dāng)前行號(hào)
%(asctime)s:打印日志的時(shí)間
%(thread)d:打印線程ID
%(threadName)s:打印線程名稱
%(process)d:打印進(jìn)程ID
%(message)s:打印日志信息
- datefmt:指定時(shí)間格式患久,同time.strftime()椅寺;
- level:設(shè)置日志級(jí)別,默認(rèn)為logging.WARNNING蒋失;
- stream:指定將日志的輸出流返帕,可以指定輸出到sys.stderr,sys.stdout或者文件篙挽,默認(rèn)輸出到sys.stderr溉旋,7. 當(dāng)stream和filename同時(shí)指定時(shí),stream被忽略嫉髓;
2. 將日志寫入到文件
2.1 將日志寫入到文件
設(shè)置logging观腊,創(chuàng)建一個(gè)FileHandler,并對(duì)輸出消息的格式進(jìn)行設(shè)置算行,將其添加到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中日志數(shù)據(jù)為州邢,
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 將日志同時(shí)輸出到屏幕和日志文件
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文件和控制臺(tái)中同時(shí)看到.
logging有一個(gè)日志處理的主對(duì)象量淌,其他處理方式都是通過addHandler添加進(jìn)去骗村,logging中包含的handler主要有如下幾種,
handler名稱:位置呀枢;作用
StreamHandler:logging.StreamHandler胚股;日志輸出到流,可以是sys.stderr裙秋,sys.stdout或者文件
FileHandler:logging.FileHandler琅拌;日志輸出到文件
BaseRotatingHandler:logging.handlers.BaseRotatingHandler;基本的日志回滾方式
RotatingHandler:logging.handlers.RotatingHandler摘刑;日志回滾方式进宝,支持日志文件最大數(shù)量和日志文件回滾
TimeRotatingHandler:logging.handlers.TimeRotatingHandler;日志回滾方式枷恕,在一定時(shí)間區(qū)域內(nèi)回滾日志文件
SocketHandler:logging.handlers.SocketHandler党晋;遠(yuǎn)程輸出日志到TCP/IP sockets
DatagramHandler:logging.handlers.DatagramHandler;遠(yuǎn)程輸出日志到UDP sockets
SMTPHandler:logging.handlers.SMTPHandler;遠(yuǎn)程輸出日志到郵件地址
SysLogHandler:logging.handlers.SysLogHandler未玻;日志輸出到syslog
NTEventLogHandler:logging.handlers.NTEventLogHandler漏益;遠(yuǎn)程輸出日志到Windows NT/2000/XP的事件日志
MemoryHandler:logging.handlers.MemoryHandler;日志輸出到內(nèi)存中的指定buffer
HTTPHandler:logging.handlers.HTTPHandler深胳;通過"GET"或者"POST"遠(yuǎn)程輸出到HTTP服務(wù)器
2.3 日志回滾
使用RotatingFileHandler,可以實(shí)現(xiàn)日志回滾铜犬,
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
#定義一個(gè)RotatingFileHandler舞终,最多備份3個(gè)日志文件,每個(gè)日志文件最大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.4 設(shè)置消息的等級(jí)
可以設(shè)置不同的日志等級(jí),用于控制日志的輸出纷宇,
日志等級(jí):使用范圍
FATAL:致命錯(cuò)誤
CRITICAL:特別糟糕的事情夸盟,如內(nèi)存耗盡、磁盤空間為空像捶,一般很少使用
ERROR:發(fā)生錯(cuò)誤時(shí)上陕,如IO操作失敗或者連接問題
WARNING:發(fā)生很重要的事件,但是并不是錯(cuò)誤時(shí)拓春,如用戶登錄密碼錯(cuò)誤
INFO:處理請(qǐng)求或者狀態(tài)變化等日常事務(wù)
DEBUG:調(diào)試過程中使用DEBUG等級(jí)释簿,如算法中每個(gè)循環(huán)的中間狀態(tài)
2.5 捕獲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")
控制臺(tái)和日志文件log.txt中輸出庶溶,
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),它等價(jià)于logger.error(msg,exc_info = True,_args)懂鸵,
logger.exception("Failed to open sklearn.txt from logger.exception")
2.6 多模塊使用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")
執(zhí)行之后匆光,在控制和日志文件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',并對(duì)它進(jìn)行了配置终息,就可以在解釋器進(jìn)程里面的其他地方通過getLogger('mainModule')得到的對(duì)象都是一樣的凉夯,不需要重新配置,可以直接使用采幌。定義的該logger的子logger劲够,都可以共享父logger的定義和配置,所謂的父子logger是通過命名來識(shí)別休傍,任意以'mainModule'開頭的logger都是它的子logger征绎,例如'mainModule.sub'。
實(shí)際開發(fā)一個(gè)application,首先可以通過logging配置文件編寫好這個(gè)application所對(duì)應(yīng)的配置人柿,可以生成一個(gè)根logger柴墩,如'PythonAPP',然后在主函數(shù)中通過fileConfig加載logging配置凫岖,接著在application的其他地方江咳、不同的模塊中,可以使用根logger的子logger哥放,如'PythonAPP.Core'歼指,'PythonAPP.Web'來進(jìn)行l(wèi)og,而不需要反復(fù)的定義和配置各個(gè)模塊的logger甥雕。
通過JSON或者YAML文件配置logging模塊
盡管可以在Python代碼中配置logging踩身,但是這樣并不夠靈活,最好的方法是使用一個(gè)配置文件來配置社露。在Python 2.7及以后的版本中挟阻,可以從字典中加載logging配置,也就意味著可以通過JSON或者YAML文件加載日志的配置峭弟。
3.1 通過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文件配置
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()