python中logging包的使用总结
1.logging简介
Python的loggingpackage提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTPGET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。
logging包中定义了Logger、Formatter、Handler和Filter等重要的类,除此之外还有config模块。
Logger是日志对象,直接提供日志记录操作的接口
Formatter定义日志的记录格式及内容
Handler定义日志写入的目的地,你可以把日志保存成本地文件,也可以每个小时写一个日志文件,还可以把日志通过socket传到别的机器上。python提供了十几种实用handler,比较常用的有StreamHandler,BaseRotatingHandler,SocketHandler,DatagramHandler,SMTPHandler等。我们可以通过Logger对象的addHandler()方法,将log输出到多个目的地。
2.Loggingpackage
在python编程中,引入了Loggingpackage,那么可以存在一个名称为root的Logging对象,以及很多其他名称的Logging对象。不同的Logger对象的Handler,Formatter等是分开设置的。
(1)logging.getLogger()如果getLogging中不带参数,那么返回的是名称为root的Logger对象,如果带参数,那么就以该参数为名称的Logger对象。同名称的Logger对象是一样的。
(2)logging.basicConfig()此方法是为名称为root的Logger对象进行配置。
(3)logging.info()logging.debug()等,使用的rootLogger对象进行信息输出。如果是用其他的Logging对象进行log输出,可以使用Logging.getLogger(name).info()来实现。
(4)日志的等级
CRITICAL=50 ERROR=40 WARNING=30 INFO=20 DEBUG=10 NOTSET=0
在python中有0,10,20,30,40,50这6个等级数值,这6个等级数值分别对应了一个字符串常量,作为等级名称,如上。但是可以通过logging.addLevelName(20,"NOTICE:")这个方法来改变这个映射关系,来定制化日志等级名称。
通过Logger对象的setLevel()方法,可以配置Logging对象的默认日志等级,只有当一条日志的等级大于等于这个默认的等级,才会输出到log文件中。
当使用logging.info(msg)输出log时,内部封装会用数字20作为日志等级数值,默认情况下20对应的是INFO,但如果通过addLevelName()修改了20对应的等级名称,那么log中打印的就将是个性化的等级名称。
3.logging包使用配置文件
在1~2中描述的,对一个Logger对象的Handler,Formatter等都是在程序中定义或绑定的。而实际上Logging的个性化的配置可以放到配置文件中。
logging的配置文件举例如下:
[loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s-%(name)s-%(levelname)s-%(message)s datefmt=
对应程序为:
importlogging importlogging.config logging.config.fileConfig("logging.conf")#采用配置文件 #createlogger logger=logging.getLogger("simpleExample") #"application"code logger.debug("debugmessage") logger.info("infomessage") logger.warn("warnmessage") logger.error("errormessage") logger.critical("criticalmessage")
4.一个常用的Logging封装工具
#!/usr/bin/envpython #-*-coding:utf-8-*- #coding=utf-8 importlogging importos classLogger(object): """ 封装好的Logger工具 """ def__init__(self,logPath): """ initial """ log_path=logPath logging.addLevelName(20,"NOTICE:") logging.addLevelName(30,"WARNING:") logging.addLevelName(40,"FATAL:") logging.addLevelName(50,"FATAL:") logging.basicConfig(level=logging.DEBUG, format="%(levelname)s%(asctime)s[pid:%(process)s]%(filename)s%(message)s", datefmt="%Y-%m-%d%H:%M:%S", filename=log_path, filemode="a") console=logging.StreamHandler() console.setLevel(logging.DEBUG) formatter=logging.Formatter("%(levelname)s[pid:%(process)s]%(message)s") console.setFormatter(formatter) logging.getLogger("").addHandler(console) defdebug(self,msg=""): """ outputDEBUGlevelLOG """ logging.debug(str(msg)) definfo(self,msg=""): """ outputINFOlevelLOG """ logging.info(str(msg)) defwarning(self,msg=""): """ outputWARNlevelLOG """ logging.warning(str(msg)) defexception(self,msg=""): """ outputExceptionstackLOG """ logging.exception(str(msg)) deferror(self,msg=""): """ outputERRORlevelLOG """ logging.error(str(msg)) defcritical(self,msg=""): """ outputFATALlevelLOG """ logging.critical(str(msg)) if__name__=="__main__": testlog=Logger("oupput.log") testlog.info("info....") testlog.warning("warning....") testlog.critical("critical....") try: lists=[] printlists[1] exceptExceptionasex: """logging.exception()输出格式: FATAL:[pid:7776]executetaskfailed.theexceptionasfollows: Traceback(mostrecentcalllast): File"logtool.py",line86,inprintlists[1] IndexError:listindexoutofrange """ testlog.exception("executetaskfailed.theexceptionasfollows:") testlog.info("++++++++++++++++++++++++++++++++++++++++++++++") """logging.error()输出格式: FATAL:[pid:7776]executetaskfailed.theexceptionasfollows: """ testlog.error("executetaskfailed.theexceptionasfollows:") exit(1)
备注:exception()方法能够完整的打印异常的堆栈信息。error()方法只会打印参数传入的信息。
备注:
按照官方文档的介绍,logging是线程安全的,也就是说,在一个进程内的多个线程同时往同一个文件写日志是安全的。但是多个进程往同一个文件写日志是不安全的。