用python做自动化测试--logging 和ConfigParser 模块

来源:互联网 发布:php curl上传图片 编辑:程序博客网 时间:2024/06/05 06:33

      在写“用python做测试” 的系列文章时,发现很多地方用到了logging和ConfigParser 模块,没有这两个模块的话,很多地方用户估计无法调试,所以还是有必要先介绍下这个2个模块的使用,熟悉java的很清楚log4j的输出。 输出信息很详细,格式可配置, 还可以定义不同log级别,方便调试和发布。ConfigParser  解析,读写ini格式的文件。

   

      看例子吧,比较直观。

#common.py

#!/usr/bin/env python#coding=utf-8import os,logging,ConfigParserdef load_config(file_name):    '''    Use ConfigParser to parse below configuration file:    [selection]:    option:value    '''    config = ConfigParser.ConfigParser()    try:        if os.path.exists(file_name):            config.read(file_name)            return config    except:        file_name," is not exit"def init_log(log_level,log_path):    #log leverl value: CRITICAL 50; ERROR 40; WARNING 30; INFO 20; DEBUG 10, NOSET 0;    logger = logging.getLogger()        hdlr = logging.FileHandler(log_path)    formatter = logging.Formatter('%(asctime)s [%(levelname)-8s %(module)s:%(lineno)d] %(message)s')    hdlr.setFormatter(formatter)    logger.addHandler(hdlr)    logger.setLevel(log_level)    return loggerif __name__=="__main__":    log=init_log(0,"monitor.log")    monitor_cfg=load_config("monitor.cfg")    for section in monitor_cfg.sections():        log.info("section is "+section)        if section=='sys':            log.debug("monitor ip:"+monitor_cfg.get(section,'ip'))                

#monitor.cfg

[sys]
#monitor_type=local or remote, if the value is local, the ip/account/password are not useful
monitor_type=remote
ip:192.168.1.2
account:root
password:root123




[memory]
command: top | head -5 |grep -i memory
# interval unit second
duration: 10


[cpu]
command: sar 1 1 |tail -1
interval: 10


把monitor.cfg保存到common.py目录下,运行common,py,输出结果

2012-11-19 16:55:01,368 [INFO     common:38] section is sys
2012-11-19 16:55:01,369 [DEBUG    common:40] monitor ip:192.168.1.2
2012-11-19 16:55:01,369 [INFO     common:38] section is cpu
2012-11-19 16:55:01,369 [INFO     common:38] section is memory


从输出信息里可以很方便的看到这个log在那个模块在第几行输出的,common:38 , 在common.py模块里面第38行输出的log

原创粉丝点击