package cn.cslg.report.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

@Slf4j
public class LogExceptionUtil {

    /**
     * @author 沈永艺
     * @date 2022-10-27
     * @description 将异常信息的格式转换为与控制台一致，用于存储到文件中
     */
    //用例： log.error(LogExceptionUtil.getMessage(e)) e为 catch (Exception e) 参数e
    public static String getMessage(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            //将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }
}
