python日志捕捉异常处理

https://docs.python.org/zh-cn/3.7/tutorial/classes.html

 

1、可参考代码

创建日志输入的目录

def getLogDir():
    # 设置输入日志的目录
    currentPath = os.getcwd()
    print("currentPath: " + currentPath)
    currentPath = currentPath + "\log"
    # 创建写日志文件目录
    if not os.path.exists(currentPath):
        os.makedirs(currentPath)
    return currentPath

设置log日志
def log(logtime):
    # 创建logger,如果参数为空则返回root logger
    logger = logging.getLogger("log")
    logger.setLevel(logging.INFO)  # 设置logger日志等级
    currentPath = getLogDir()
    # 设置日志文件
    logFileName = currentPath + "\\" + "test_" + logtime + ".log"
    # 这里进行判断,如果logger.handlers列表为空,则添加,否则,直接去写日志
    if not logger.handlers:
        # 创建handler
        fh = logging.FileHandler(logFileName, encoding="utf-8")
        ch = logging.StreamHandler()
        # 设置输出日志格式
        formatter = logging.Formatter(fmt="%(asctime)s %(name)s %(filename)s %(message)s", datefmt="%Y/%m/%d %X")
        # 为handler指定输出格式
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # 为logger添加的日志处理器
        logger.addHandler(fh)
        logger.addHandler(ch)
    return logger


def screenshot(nowTime, d):
    currentPath = getLogDir()
    time1_str = currentPath + "\\" + "img_" + nowTime + ".png"
    d.screenshot(time1_str)


# 连接设备
devices = '47Q6R16924003239'
processName = 'cn.dd.test'
d = u2.connect(devices)
print(d.info)

对异常或错误的逻辑处理

try:
    main.start(d, processName)
except Exception as e:
    # 获取当前时间
    nowTime = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
    # 打印错误日志
    traceback.print_exc()
    # 输入错误日志到文件
    logger = log(nowTime)
    logger.info("dd")
    logger.error("错误日志:\n" + traceback.format_exc())
    # 对错误界面截屏
    screenshot(nowTime, d)

最新回复 (0)
/jishu nwLAeBeObh3x1fxqBaaooNm12kaZoKer3v1Qcw_3D_3D 4488683
8