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

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')

 

微信公众号搜索“自动化测试实战”或扫描下方二维码添加关注~~~

还请大家多多提意见,我们慢慢来,重要的是学会~~~如果你觉得对你有帮助,也欢迎大家转发,船长先谢谢各位啦~~~

posted @ 2017-10-24 09:55  孟船长  阅读(265)  评论(0编辑  收藏  举报