Python自动化测试中,日志输出功能是不能缺少的一部分。让我们来看看如何实现日志的输出吧
一、控制台输出日志
def get_logger():
try:
if not os.path.exists('./Logs'):
os.makedirs('./Logs')
except Exception as e:
pring(e)
FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT, datefmt='%Y-%m-%d %H:%M:%S')
return logging
二、日志输出到文件
def get_logger():
try:
if not os.path.exists('./Logs'):
os.makedirs('./Logs')
except Exception as e:
pring(e)
FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT, datefmt='%Y-%m-%d %H:%M:%S', filename='./Logs/test.log',
filemode='w')
return logging
三、日志控制台输出+输出到文件
1 def uilog(logger_name=time.strftime('test-'+'%Y%m%d%H%M%S.log', time.localtime(time.time()))): 2 # 创建一个logger 3 logger = logging.getLogger(logger_name) 4 logger.setLevel(logging.INFO) 5 #调试用 6 if not os.path.exists('../Logs'): 7 os.makedirs('../Logs') 8 log_file_path = os.path.join('../Logs', logger_name) 9 #打包用 10 # if not os.path.exists('./Logs'): 11 # os.makedirs('./Logs') 12 # log_file_path = os.path.join('./Logs', logger_name) 13 14 # 创建一个handler写入所有日志 15 fh = logging.FileHandler(log_file_path) 16 fh.setLevel(logging.INFO) 17 # 创建一个handler写入错误日志 18 eh = logging.FileHandler(log_file_path) 19 eh.setLevel(logging.ERROR) 20 # 创建一个handler输出到控制台 21 ch = logging.StreamHandler() 22 ch.setLevel(logging.INFO) 23 24 # 定义日志输出格式:以时间-日志器名称-日志级别-日志内容的形式展示 25 log_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s","%Y-%m-%d %H:%M:%S") 26 # 将定义好的输出形式添加到handler 27 fh.setFormatter(log_formatter) 28 ch.setFormatter(log_formatter) 29 eh.setFormatter(log_formatter) 30 31 # 给logger添加handler 32 logger.addHandler(fh) 33 logger.addHandler(eh) 34 logger.addHandler(ch) 35 return logger
END