[自动化测试]自定义日志
1.配置文件设置(此处使用的为yaml配置文件)
log: file_name: test_case.log # 输出日志文件名 backup: 5 # 备份名 console_level: DEBUG # 控制台输出等级 file_level: DEBUG # 文件输出等级 # pattern: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' # 打 # 印输出格式 pattern: '%(asctime)s - %(message)s' # 打印输出格式
2.用于yaml文件读取
import yaml import os # 通过配置文件获取配置信息 from comm.settings import * class YamlReader: def __init__(self, yamlfilepath): if os.path.exists(yamlfilepath): self.yamlfilepath = yamlfilepath else: raise FileNotFoundError("文件不存在!") self._data = None @property def first_reader_data(self): if not self._data: with open(self.yamlfilepath, "rb") as f: self._data = list(yaml.safe_load_all(f)) return self._data class SheetTypeError(Exception): # 自定义异常类 pass
3.获取数据
from comm import ymal_reader from comm.settings import reader_exl_path, reader_yml_path class Config: def __init__(self): if ymal_reader.YamlReader: self.config = ymal_reader.YamlReader(reader_yml_path).first_reader_data else: self.config = ymal_reader.ExcelReader(reader_exl_path).get_excel_data def get(self, element, index=0): return self.config[index].get(element) # 单元测试 if __name__ == '__main__': f = Config().get("local_url") print(f)
4.Log方法
import logging import os from logging.handlers import TimedRotatingFileHandler from comm.settings import LOG_DIR from comm.useyaml import Config class Logger: def __init__(self, logger_name="framework"): self.logger = logging.getLogger(logger_name) logging.root.setLevel(logging.INFO) c = Config().get("log") # 日志文件名 self.log_file_name = c.get("file_name") if c and c.get("file_name") else "test_xx" # 保留日志个数 self.backup_count = c.get("backup") if c and c.get("backup") else 5 # 日志输出级别 self.console_output_level = c.get("console_level") if c and c.get("console_level") else "WARNING" self.file_output_level = c.get('file_level') if c and c.get('file_level') else 'DEBUG' # 日志输出格式 pattern = c.get('pattern') if c and c.get('pattern') else '%(asctime)s - %(name)s - %(levelname)s - %(message)s' self.formatter = logging.Formatter(pattern) def get_logger(self): # 避免重复日志 if not self.logger.handlers: # 每天重新创建一个日志文件,最多保留backup_count份 file_handler = TimedRotatingFileHandler(filename=os.path.join(LOG_DIR, self.log_file_name), when='D', interval=1, backupCount=self.backup_count, delay=True, encoding='utf-8' ) console_handler = logging.StreamHandler() console_handler.setLevel(self.console_output_level) file_handler.setLevel(self.file_output_level) file_handler.setFormatter(self.formatter) console_handler.setFormatter(self.formatter) self.logger.addHandler(file_handler) self.logger.addHandler(console_handler) return self.logger Logger = Logger().get_logger() #单元测试 if __name__ == '__main__': Logger.debug('debug message') Logger.info('info message') Logger.warning('warning message') Logger.error('error message') Logger.critical('critical message')
学习,学习,学习!
学习是为了更好的未来,不要让别人瞧不起你,加油!!!