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

时间:2017-10-24 10:52:16   收藏:0   阅读:230

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函数各参数:

 

 

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‘)
?

 

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

技术分享

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

原文:http://www.cnblogs.com/captainmeng/p/7722079.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!