美文网首页
自定义日志方法

自定义日志方法

作者: ShrJanLan | 来源:发表于2022-05-11 20:58 被阅读0次
    public static void infoLog(String logContent) {
        simpleLog("INFO", logContent);
    }
    
    public static void debugLog(String logContent) {
        simpleLog("DEBUG", logContent);
    }
    
    public static void errorLog(String logContent) {
        simpleLog("ERROR", logContent);
    }
    
    public static void errorLog(Exception e) {
        simpleLog("ERROR", ExceptionUtils.getStackTrace(e));
    }
    
    public static void simpleLog(String logLevel,String logContent) {
        try {
            SimpleDateFormat logDateSdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat logTimeSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String logFilePath = logLevel.toLowerCase() + logDateSdf.format(new Date()) + ".log";
            File logFile = new File(logFilePath);
            if (!logFile.isFile()) {
                logFile.createNewFile();
            }
            try (OutputStream logOut = new FileOutputStream(logFilePath,true);
                 OutputStreamWriter logOutWriter = new OutputStreamWriter(logOut, StandardCharsets.UTF_8)) {
                logOutWriter.write(logTimeSdf.format(new Date()));
                logOutWriter.write(" [");
                logOutWriter.write(Thread.currentThread().getName());
                logOutWriter.write("] - [");
                logOutWriter.write(logLevel);
                logOutWriter.write("] ");
                logOutWriter.write(logContent);
                logOutWriter.write("\r\n");
                logOutWriter.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    相关文章

      网友评论

          本文标题:自定义日志方法

          本文链接:https://www.haomeiwen.com/subject/qmjjurtx.html