日志模块封装
author = 'damao'
import logging
import sys
import time
"""
日志级别排序:critical > error > warning > info > debug
debug : 打印全部的日志,详细的信息,通常只出现在诊断问题上
info : 打印info,warning,error,critical级别的日志,确认一切按预期运行
warning : 打印warning,error,critical级别的日志,一个迹象表明,一些意想不到的事情发生了,或表明一些问题在不久的将来(例如。磁盘空间低”),这个软件还能按预期工作
error : 打印error,critical级别的日志,更严重的问题,软件没能执行一些功能
criticl : 打印critical级别,一个严重的错误,这表明程序本身可能无法继续运行
"""
class LogHandler(object):
def __init__(self,logger=None):
# 获取logger实例
self.logger = logging.getLogger(logger)
# 设置日志的最低级别,默认是warning级别
self.logger.setLevel(logging.DEBUG) # 设置日志级别为debug级别
# 文件日志
self.now = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())) # 获取当前时间
self.log_file_name = 'auto_test_' + self.now + '.log'
# 指定logger输出格式
formatter = logging.Formatter('[%(name)-4s %(asctime)s %(filename)s %(module)s %(levelname)s] ===》 %(message)s')
# log_file_path = '..\\logs\\'
# print(log_file_name)
log_file_handler = logging.FileHandler('.\\logs\\log_file\\{a}'.format(a=self.log_file_name),mode='w',encoding='utf-8') # 写入日志文件到本地
log_file_handler.setFormatter(formatter) # 设置日志输入格式
# 控制台日志
console_handler = logging.StreamHandler(sys.stdout) # 控制台输出日志
console_handler.formatter = formatter # 设置控制台输出的格式
# 为logger添加日志处理器
self.logger.addHandler(log_file_handler) # 日志文件处理器
self.logger.addHandler(console_handler) # 控制台处理器
# # 用pop把logger的handler列表中的handler移除
# self.logger.handlers.pop() # 解决日志打印重复的问题
# 关闭打开的文件
log_file_handler.close()
console_handler.close()
def getlog(self):
return self.logger
封装模块测试
if __name__ == "__main__":
a = LogHandler("damao").getlog()
# 输出不同级别的log
a.debug('this is debug infosad打 第三方 发')
a.info('this is information')
a.warn('this is warning message')
a.error('this is error message')
a.fatal('this is fatal message, it is same as logger.critical')
a.critical('this is critical message')
service_name = "Booking"
a.error('%s service is down!' % service_name) # 使用python自带的字符串格式化,不推荐
a.error('%s service is down!', service_name) # 使用logger的格式化,推荐
a.error('%s service is %s!', service_name, 'down') # 多参数格式化
a.error('{} service is {}'.format(service_name, 'down')) # 使用format函数,推荐
日志封装模块的使用
author = 'damao'
import unittest
from common import base
import json
from ddt import ddt,data,unpack
from logs import my_logger
logger = my_logger.LogHandler("damao").getlog()
@ddt
class TestDemo(unittest.TestCase):
def setUp(self):
interface_path = 'get'
self.url = base.get_url(interface_path)
logger.info("接口地址:{a}".format(a=self.url))
# @data({'a': 1},123,{'c': 1},1,233)
@data(2,'httpbin.org')
def test_get(self,a):
"""接口测试用例"""
params = {'c': 1}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Accept-Encoding': 'gzip, deflate',
'Accept': '*/*',
'Connection': 'keep-alive'
}
res = base.run_mothed(url=self.url,params=params,headers=headers,mothed='get')
logger.info('请求体参数:params:{a}'.format(a=params))
logger.info('请求头参数:header:{b}'.format(b=headers))
print(json.dumps(res, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ':')))
# 断言
result = res.get('headers').get('Host')
if self.assertEqual(result,a) is True:
logger.info("用例执行成功,断言正确")
else:
logger.info("用例执行成功,断言失败")
# logger.info("断言结果:{a}".format(a=bool(rult)))
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
配置日志输出颜色
# created 27.06.2019
# author = "hang"
import datetime
import logging
import time
from colorama import Fore, Style
from configs.path_config import project_dir
from configparser import ConfigParser
project_dir = project_dir()
config = ConfigParser()
config.read(f"{project_dir}\\configs\\test.ini", encoding="UTF-8")
class MyLog(object):
def __init__(self, logger):
"""
指定保存日志的文件路径,日志级别,以及调用文件
将日志存入到指定的文件中
:param logger: 定义对应的程序模块名name,默认为root
"""
# 创建一个logger
self.logger = logging.getLogger(name=logger)
self.logger.setLevel(logging.DEBUG) # 指定最低的日志级别 critical > error > warning > info > debug
self.log_time = time.strftime("%Y-%m-%d", time.localtime())
self.log_name = project_dir + f"{config['logout']['sys_log_path']}\\system-run-{self.log_time}.log"
fh = logging.FileHandler(self.log_name, 'a') # 追加模式 这个是python2的
# fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8') # 这个是python3的
fh.setLevel(logging.INFO)
# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# 定义handler的输出格式
formatter = logging.Formatter('%(message)s')
# '[%(levelname)s] [%(filename)s->%(funcName)s line:%(lineno)d] %(asctime)s %(message)s'
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# 给logger添加handler
self.logger.addHandler(fh)
self.logger.addHandler(ch)
# 添加下面一句,在记录日志之后移除句柄
# self.logger.removeHandler(ch)
# self.logger.removeHandler(fh)
# 关闭打开的文件
fh.close()
ch.close()
def debug(self, msg):
"""
定义输出的颜色debug--white,info--green,warning/error/critical--red
:param msg: 输出的log文字
:return:
"""
self.logger.debug(Fore.WHITE + f"[DEBUG] {self.get_now_time()} - " + str(msg) + Style.RESET_ALL)
def info(self, msg):
self.logger.info(Fore.GREEN + f"[INFO] {self.get_now_time()} - " + str(msg) + Style.RESET_ALL)
def warning(self, msg):
self.logger.warning(Fore.RED + f"[WARNING] {self.get_now_time()} - " + str(msg) + Style.RESET_ALL)
def error(self, msg):
self.logger.error(Fore.RED + f"[ERROR] {self.get_now_time()} - " + str(msg) + Style.RESET_ALL)
def critical(self, msg):
self.logger.critical(Fore.RED + f"[CRITICAL] {self.get_now_time()} - " + str(msg) + Style.RESET_ALL)
@staticmethod
def get_now_time():
return datetime.datetime.now()
if __name__ == '__main__':
log = MyLog(logger="test")
log.debug("debug")
log.info("info")
log.error("error")
log.warning("warning")
log.critical("critical")
网友评论