搜索
首页后端开发Python教程python中关于logging库的使用总结

python中关于logging库的使用总结

Oct 18, 2017 am 11:02 AM
loggingpython总结

Python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用,下面这篇文章主要给大家介绍了关于python中logging库使用的一些知识总结,文中给出了详细的示例代码,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

最近因为工作的需要,在写一些python脚本,总是使用print来打印信息感觉很low,所以抽空研究了一下python的logging库,来优雅的来打印和记录日志,下面话不多说了,来一起看看详细的介绍吧。

一、简单的将日志打印到屏幕:


import logging

logging.debug('This is debug message')  #debug
logging.info('This is info message')   #info
logging.warning('This is warning message') #warn

屏幕上打印:WARNING:root:This is warning message

默认情况下,会打印WARNING级别的日志

  • DEBUG:详细信息,调试信息。

  • INFO:确认一切按预期运行。

  • WARNING:表明发生了一些意外,或者不久的将来会发生问题(如‘磁盘满了')。软件还是在正常工作。

  • ERROR:由于更严重的问题,软件已不能执行一些功能了。

  • CRITICAL:严重错误,表明软件已不能继续运行了。

二、通过basicConfig函数来对日志的输入格式和方法进行配置


import logging

logging.basicConfig(level=logging.DEBUG,
    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    datefmt='%Y-%m-%d %a %H:%M:%S',
    filename='test.log',
    filemode='w')
 
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

以上代码不会在屏幕上打印日志,而是会在当前目录生成test.log的日志文件,日志被打印在日志文件中:

2017-10-16 Mon 10:05:17 testlogging.py[line:25] DEBUG This is debug message

2017-10-16 Mon 10:05:17 testlogging.py[line:26] INFO This is info message

2017-10-16 Mon 10:05:17 testlogging.py[line:27] WARNING This is warning message

  • 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.WARNING

  • stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

三、同时将日志输出到屏幕和日志文件


#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

插入以上代码就可以同时在屏幕上打印出日志

屏幕上打印:

root : INFO This is info message

root : WARNING This is warning message

文件中打印:

2017-10-16 Mon 10:20:07 testlogging.py[line:46] DEBUG This is debug message

2017-10-16 Mon 10:20:07 testlogging.py[line:47] INFO This is info message

2017-10-16 Mon 10:20:07 testlogging.py[line:48] WARNING This is warning message

四、通过配置文件配置日志


#logger.conf
[loggers]
#定义logger模块,root是父类,必需存在的,其它的是自定义。 
keys=root,infoLogger,warnlogger

[logger_root] 
level=DEBUG       #level  级别,级别有DEBUG、INFO、WARNING、ERROR、CRITICAL
handlers=infohandler,warnhandler #handlers 处理类,可以有多个,用逗号分开

[logger_infoLogger]     #[logger_xxxx] logger_模块名称
handlers=infohandler
qualname=infoLogger     #qualname logger名称,应用程序通过 logging.getLogger获取。对于不能获取的名称,则记录到root模块。
propagate=0       #propagate 是否继承父类的log信息,0:否 1:是

[logger_warnlogger]
handlers=warnhandler
qualname=warnlogger
propagate=0

###############################################
#定义handler
[handlers]
keys=infohandler,warnhandler

[handler_infohandler]
class=StreamHandler     #class handler类名
level=INFO       #level 日志级别
formatter=form02      #formatter,下面定义的formatter
args=(sys.stdout,)     #args handler初始化函数参数

[handler_warnhandler]
class=FileHandler
level=WARN
formatter=form01
args=('logs/deploylog.log', 'a')

###############################################
# 定义格式化输出
[formatters]
keys=form01,form02

[formatter_form01]
format=%(message)s %(asctime)s
datefmt=%Y-%m-%d %H:%M:%S

[formatter_form02]
format=%(asctime)s %(levelname)s %(message)s
datefmt=%Y-%m-%d %H:%M:%S

日志格式

  • %(asctime)s 年-月-日 时-分-秒,毫秒 2013-04-26 20:10:43,745

  • %(filename)s 文件名,不含目录

  • %(pathname)s 目录名,完整路径

  • %(funcName)s 函数名

  • %(levelname)s 级别名

  • %(lineno)d 行号

  • %(module)s 模块名

  • %(message)s 消息体

  • %(name)s 日志模块名

  • %(process)d 进程id

  • %(processName)s 进程名

  • %(thread)d 线程id

  • %(threadName)s 线程名

测试配置文件


from logging.config import fileConfig

fileConfig('logger.conf')
logger=logging.getLogger('infoLogger')
logger.info('test1')
logger_error=logging.getLogger('warnhandler')
logger_error.warn('test5')

总结

以上是python中关于logging库的使用总结的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy阵列上可以执行哪些常见操作?在Numpy阵列上可以执行哪些常见操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的数据分析中如何使用阵列?Python的数据分析中如何使用阵列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表的内存足迹与python数组的内存足迹相比如何?列表的内存足迹与python数组的内存足迹相比如何?May 02, 2025 am 12:08 AM

列表sandnumpyArraysInpyThonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,withoverHeadeBheadaroundAroundaroundaround64bytaround64bitson64-bitsysysysyssyssyssyssyssyssysssys2)

部署可执行的Python脚本时,如何处理特定环境的配置?部署可执行的Python脚本时,如何处理特定环境的配置?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehavecorrectlyacrycrossdevelvermations,登台和生产,USETHESTERTATE:1)Environment varriablesforsimplesettings,2)configurationFilesForefilesForcomPlexSetups,3)dynamiCofforAdaptapity.eachmethodofferSuniquebeneiquebeneiquebeneniqueBenefitsaniqueBenefitsandrefitsandRequiresandRequireSandRequireSca

您如何切成python阵列?您如何切成python阵列?May 01, 2025 am 12:18 AM

Python列表切片的基本语法是list[start:stop:step]。1.start是包含的第一个元素索引,2.stop是排除的第一个元素索引,3.step决定元素之间的步长。切片不仅用于提取数据,还可以修改和反转列表。

在什么情况下,列表的表现比数组表现更好?在什么情况下,列表的表现比数组表现更好?May 01, 2025 am 12:06 AM

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/删除,2)储存的二聚体和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

如何将Python数组转换为Python列表?如何将Python数组转换为Python列表?May 01, 2025 am 12:05 AM

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,请考虑performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。