您的位置:首页 > 编程语言 > Python开发

python中logging库的使用总结

2017-10-18 10:52 603 查看

前言

最近因为工作的需要,在写一些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库 使用