Python 中 Logging 模块使用详情
1.为什么要用logging模块
在实际应用中,日志文件十分重要,通过日志文件,我们知道程序运行的细节;同时,当程序出问题时,我们也可以通过日志快速定位问题所在。在我们写程序时,也可以借助logging模块的输出信息来调试代码。
但是很多人还是在程序中使用print()函数来输出一些信息,比如:
print'Startreadingdatabase'
records=model.read_recrods()
print'#records',records
print'Updatingrecord...'
model.update_records(records)
print'done'
这样用的话缺点很明显,当程序写好运行时,我们要把这些print()函数删掉,在简单的的程序中用还行,当程序比较复杂时,这个办法很低效。
如果使用logging模块,看看效果:
importlogging
logging.basicConfig(level=logging.INFO)
logger=logging.getLogger(__name__)
logger.info('Startreadingdatabase')
#readdatabasehere
records={'john':55,'tom':66}
logger.debug('Records:%s',records)
logger.info('Updatingrecords...')
#updaterecordshere
logger.info('Finishupdatingrecords')
运行结果如下:
INFO:__main__:Startreadingdatabase
INFO:__main__:Updatingrecords...
INFO:__main__:Finishupdatingrecords
你也许会问,这和print()函数有什么区别呢?区别就在于,logging模块可以通过改变level来控制一些语句是否被输出,比如当我们把level改成DEBUG级别:
logging.basicConfig(level=logging.DEBUG)
得到输出如下:
INFO:__main__:Startreadingdatabase
DEBUG:__main__:Records:{'john':55,'tom':66}
INFO:__main__:Updatingrecords...
INFO:__main__:Finishupdatingrecords
2.logging模块介绍
logging模块是python自带的一个包,因此在使用的时候,不必安装,只需要import即可。有5个level,分别是debug,主要是查看一下程序运行的信息,一般是调试程序要看的信息;info,是我们看程序是否如预料执行的信息;warn,意料之外的,但是不影响程序运行;error和critical就是一些比较严重的问题,会影响程序运行。默认leval是warn,这个时候debug级别和info级别就不会被输出到日志里了。如果想要看到这些信息,就需要进行一些设置。
3.基础设置
我们主要调用basicConfig(***kwargs*)这个函数对logging进行设置。
常用的参数如下:
·level:主要调整logging的级别
·filename:输出日志的路径
·filemode:直接写入还是追加写入
·format:输出的格式
我们通过调整format,可以输出我们想要的格式,比如:
importlogging
logging.basicConfig(format='%(asctime)s-%(message)s',datefmt='%d-%b-%y%H:%M:%S')
logging.warning('Adminloggedout')
结果是:
12-Jul-1820:53:19-Adminloggedout
这就是在format参数中设置了时间的,所以得到了时间,我们可以输出多种想要的信息
以上内容为大家介绍了Python中Logging模块使用详情,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关推荐HOT
更多>>
python字符串需要注意的语法问题
python字符串需要注意的语法问题语法错误是经常发生的一个错误。当一个程序包含非法的Python代码时,会产生语法错误。举例来说,在包含单引号的...详情>>
2023-11-14 18:23:24
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15