一、项目结构如图

二、编写logger工具类
logger_utils.py
import os
import logging
import platform
# 一般为项目名称
logger = logging.getLogger("autotest")
logger.setLevel(logging.DEBUG)
# 设置日志文件打印格式,见文档https://docs.python.org/zh-cn/3.7/library/logging.html#logger-objects
logPath = ""
if platform.system().lower() == 'windows':
print("windows")
# 获取autotest,也就是项目的根路径
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = curPath[:curPath.find("AutoTest\\") + len("autotest\\")]
# 获取autotest.log文件的路径
logPath = os.path.abspath(rootPath + 'logs\\autotest.log')
print(curPath)
print(rootPath)
else:
curPath = os.path.abspath(os.path.dirname(__file__))
# 获取autotest,也就是项目的根路径
rootPath = curPath[:curPath.find("autotest/") + len("autotest/")]
# 获取autotest.log文件的路径
logPath = os.path.abspath(rootPath + 'logs/autotest.log')
print(curPath)
print(rootPath)
print(logPath)
format = logging.Formatter('[%(asctime)s][%(levelname)s][%(funcName)s][%(message)s]')
handler = logging.FileHandler(filename=logPath, mode='a', encoding='utf8')
handler.setFormatter(format)
# 设置控制台打印日志格式
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(format)
logger.addHandler(handler)
logger.addHandler(stream_handler)
三、使用logger工具类
test_log.py
from utils.logger_utils import logger person = "我是一个好人" # 记得加上f logger.debug(f'打印日志信息为:{person}')
生成autotest.log

浙公网安备 33010602011771号