Python+Selenium进行UI自动化测试项目中,常用的小技巧4:日志打印,longging模块(控制台和文件同时输出)
2016-06-23 22:39
1026 查看
在前段时间,为了给项目中加入日志功能,就想到了 logging 模块,百度logging一大推,都是各种复制的,并没有找到自己想要的结果;我的目的很简单,就是:在把日志写入文件的同时在控制台输出,更加方便调试,我下面的代码就满足这个功能:
ps:
self.logname = commonparameter.log_path + '\\' + 'Log' +time.strftime('%Y-%m-%d') + '.log' #你存放日志的路径
#coding=utf-8 import logging import time import commonparameter class Log: def __init__(self): self.logname = commonparameter.log_path + '\\' + 'Log' +time.strftime('%Y-%m-%d') + '.log' def printconsole(self, level, message): # 创建一个logger logger = logging.getLogger('mylogger') logger.setLevel(logging.DEBUG) # 创建一个handler,用于写入日志文件 fh = logging.FileHandler(self.logname,'a') fh.setLevel(logging.DEBUG) # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # 定义handler的输出格式 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # 给logger添加handler logger.addHandler(fh) logger.addHandler(ch) # 记录一条日志 if level == 'info': logger.info(message) elif level == 'debug': logger.debug(message) elif level == 'warning': logger.warning(message) elif level == 'error': logger.error(message) logger.removeHandler(ch) logger.removeHandler(fh) def debug(self,message): self.printconsole('debug', message) def info(self,message): self.printconsole('info', message) def warning(self,message): self.printconsole('warning', message) def error(self,message): self.printconsole('error', message) if __name__ == '__main__': log = Log() log.info('info msg1000013333') log.debug('debug msg') log.warning('warning msg') log.error('error msg')
ps:
self.logname = commonparameter.log_path + '\\' + 'Log' +time.strftime('%Y-%m-%d') + '.log' #你存放日志的路径
相关文章推荐
- python3.5安装BeautifSoup
- iPython快捷键使用技巧简约版
- Python爬虫----1
- 有道词典python 代码(暂有缺憾)
- 【Python学习日记】递归实现hanoi塔
- 用Scrapy抓取Yahoo! WOEID
- python-implement global var using attr of function
- python科学计算_numpy_常规函数与排序
- python发送qq邮件
- Python Django 安装(No module named setuptools)解决方案
- Python安装Mysql模块MySQLdb详解
- Python 波浪线与补码
- python科学计算_numpy_简单的多项式应用
- Python匹配对象与索引使用
- 机器学习实战(一)--K近邻算法实现
- python列表
- Python 小练习 倒序输出
- Python――flask-sqlalchemy 自动生成符合Sqlachemy的Model:sqlautocode/sqlacodegen使用方式
- 字典的基本操作
- python中urlencode方法