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

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

   

      看例子吧,比较直观。

#common.py

#!/usr/bin/env python
#coding=utf-8

import os,logging,ConfigParser


def 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 logger

if __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

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值