首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >接口测试基础——第4篇logging模块

接口测试基础——第4篇logging模块

作者头像
孟船长
发布2018-05-18 18:06:22
5110
发布2018-05-18 18:06:22
举报

Logging:日志记录是为了跟踪记录软件运行时,发生的事件,包括出错,提示信息等等。

log日志级别:日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET;模块默认级别为WARNING,即当且仅当等于或高于WARNING的事件会被记录下来,其余的忽略不计。

1、打印到屏幕:

import logging

logging.warn("this logging warn")
logging.info("this is logging info")

屏幕打印为:

WARNING:root:this logging warn

2、打印到指定文件

import logging
LOG_FILENAME="/root/project/log.txt"
logging.basicConfig(filename=LOG_FILENAME,level=logging.INFO)
logging.info("This message should go to the log file")

3、通过logging.basicConfig函数对日志的输出格式及方式做相关配置

import logging

# LOG_FILENAME = r"C:\Users\weiming\Desktop\log.txt"
# logging.basicConfig(filename=LOG_FILENAME, level=logging.INFO)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d]  %(levelname)s %(message)s',
                    datefmt= '%a, %d %b %Y %H:%M:%S',
                    filename='logs.log',
                    filemode='w')
logging.debug('debug information')
logging.info('info information')
logging.warn('warning information')

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被忽略

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

import logging

# LOG_FILENAME = r"C:\Users\weiming\Desktop\log.txt"
# logging.basicConfig(filename=LOG_FILENAME, level=logging.INFO)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d]  %(levelname)s %(message)s',
                    datefmt= '%a, %d %b %Y %H:%M:%S',
                    filename='logs.log',
                    filemode='w')

# 定义一个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)

logging.debug('debug information')
logging.info('info information')
logging.warn('warning information')
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-09-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 自动化测试实战 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档