自定义日志文件
一、用途
系统日志具备通用性,但是特殊场景下需要快速定位日志,比如接口相关记录、数据处理记录、上线初期功能运行情况记录等,此时自定义的日志输出就可以帮助快捷进行记录查询
二、相关代码
import java.io.Closeable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import wt.util.WTProperties;
public class MyLogger {
/**
* 日志文件的大小上限,默认9M,单位是字节
*/
public long maxSize = 9216 * 1024;
/**
* 日志文件的路径,要精确到文件
*/
private String filePath;
/**
* 用户输入的日志文件的路径,要精确到文件
*/
private String logPath;
/**
* 要写入的内容添加到这里
*/
private StringBuffer context;
/**
* 是否在每次写入日志时添加写入时间,默认是
*/
private boolean hasTimeStamp = true;
private static final String FILE_TYPE = ".log";
public void setHasTimeStamp(boolean hasTimeStamp) {
this.hasTimeStamp = hasTimeStamp;
}
public MyLogger(String filePath) {
try {
logPath = WTProperties.getLocalProperties().getProperty("wt.home") + File.separator + filePath;
context = new StringBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setMaxSize(long maxSize) {
this.maxSize = maxSize;
}
/**
* 直接写入
*
* @param info 要写入的信息
* @throws IOException 写入失败
*/
public void directWriteIn(String info) {
this.writeIn(info);
}
/**
* 写入log日志
*/
public void writeInAll() throws IOException {
this.writeIn(context.toString());
}
/**
* 检查是否有待写入内容
*
* @return result
*/
public boolean contextIsNull() {
return context.length() == 0;
}
/**
* 写入log日志
*/
private synchronized void writeIn(String info) {
FileWriter out = null;
PrintWriter pw = null;
try {
checkAndSetFilePath();
out = new FileWriter(filePath, true);
pw = new PrintWriter(out);
if (hasTimeStamp) {
pw.println("<" + getTime() + "> " + info);
} else {
pw.println(info);
}
pw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(pw);
close(out);
}
}
public MyLogger add(String info) {
context.append(info).append(System.getProperty("line.separator"));
return this;
}
/**
* 设置输出文件名 大于maxSize找下一个文件 否则新建一个文件
*
* @return
* @throws IOException 文件路径错误
*/
private void checkAndSetFilePath() throws IOException {
File file = new File(logPath);
String fileName = file.getName();
String currentFileName = "";
if (!fileName.endsWith(FILE_TYPE)) {
throw new IOException("请输入正确的文件路径:" + logPath);
}
File parentDir = file.getParentFile();
if (!parentDir.exists()) {
boolean isSuccess = parentDir.mkdirs();
if (!isSuccess) {
throw new IOException("创建文件夹失败:" + parentDir);
}
}
File[] files = parentDir.listFiles();
// 遍历父文件夹中的所有文件
if (null != files) {
for (File temp : files) {
String name = temp.getName();
boolean isSameLogFile =
temp.isFile() && name.endsWith(FILE_TYPE) && name.startsWith(fileName.replace(FILE_TYPE, ""));
if (isSameLogFile) {
long fileSize = temp.length();
if (fileSize < maxSize) {
currentFileName = name;
}
}
}
}
if (currentFileName.isEmpty()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
filePath = logPath.replace(FILE_TYPE, "_" + timeForFileName() + FILE_TYPE);
} else {
filePath = parentDir.getAbsolutePath() + File.separator + currentFileName;
}
}
/**
* 获取系统当前时间
*
* @return 当前时间
*/
public static String getTime() {
Date date = new Date();
String timeFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = getDateFormat(timeFormat);
return sdf.format(date);
}
/**
* 获取系统当前日期
*
* @return 当前日期
*/
public static String getDate() {
Date date = new Date();
String timeFormat = "yyyy-MM-dd";
SimpleDateFormat sdf = getDateFormat(timeFormat);
return sdf.format(date);
}
/**
* 提供时间格式
*
* @param timeFormat format
* @return 时间Str
*/
public static String getTime(String timeFormat) {
Date date = new Date();
SimpleDateFormat sdf = getDateFormat(timeFormat);
return sdf.format(date);
}
/**
* 获取时间格式
*
* @param timeFormat format
* @return 时间格式
*/
public static SimpleDateFormat getDateFormat(String timeFormat) {
SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
return sdf;
}
/**
* 获取系统当前时间 去掉了文件路径中不允许存在的符号
*
* @return
*/
public static String timeForFileName() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
return sdf.format(date);
}
/**
* 关闭流
*
* @param closeable 可关闭流
*/
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
三、用法示例
public static void logTest(String logPath) {
MyLogger log = new MyLogger(logPath);
log.directWriteIn("这是一条测试数据");
}
四、补充
1、写入文件出现乱码解决
修改writeIn方法
private synchronized void writeIn(String info) {
BufferedWriter bufferedWriter = null;
PrintWriter printWriter = null;
try {
checkAndSetFilePath();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8"));
printWriter = new PrintWriter(bufferedWriter);
if (hasTimeStamp) {
printWriter.println("<" + getTime() + "> " + info);
} else {
printWriter.println(info);
}
printWriter.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(printWriter);
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}