自定义日志方法
2022-05-11 本文已影响0人
ShrJanLan
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();
}
}