今天尝试模型LOG4J的按设定大小来输出日志文件,下面是我的实现:
public
class MyFileWriter {
private long byteCount;
private int index;
private String fileName;
private long maxFileSize;
private FileWriter writer;
public static final int TYPE_MB = 1;
public static final int TYPE_KB = 2;
public void setFileSize( long size) {
this.maxFileSize = size;
}
public void setFileSize( long size, int type) {
int factor;
switch (type) {
case TYPE_KB:
factor = 1024;
break;
case TYPE_MB:
factor = 1024 * 1024;
break;
default:
factor = 1;
break;
}
this.maxFileSize = size * factor;
}
public MyFileWriter(File file) throws IOException {
writer = new FileWriter(file);
fileName = file.getAbsolutePath();
}
public void write(String str) throws IOException {
byteCount += str.getBytes().length;
if (byteCount >= maxFileSize) {
this.writer.close();
index++;
byteCount = 0;
this.writer = new FileWriter( new File(fileName + "." + index));
}
this.writer.write(str);
}
public void close() throws IOException {
writer.close();
}
}
private long byteCount;
private int index;
private String fileName;
private long maxFileSize;
private FileWriter writer;
public static final int TYPE_MB = 1;
public static final int TYPE_KB = 2;
public void setFileSize( long size) {
this.maxFileSize = size;
}
public void setFileSize( long size, int type) {
int factor;
switch (type) {
case TYPE_KB:
factor = 1024;
break;
case TYPE_MB:
factor = 1024 * 1024;
break;
default:
factor = 1;
break;
}
this.maxFileSize = size * factor;
}
public MyFileWriter(File file) throws IOException {
writer = new FileWriter(file);
fileName = file.getAbsolutePath();
}
public void write(String str) throws IOException {
byteCount += str.getBytes().length;
if (byteCount >= maxFileSize) {
this.writer.close();
index++;
byteCount = 0;
this.writer = new FileWriter( new File(fileName + "." + index));
}
this.writer.write(str);
}
public void close() throws IOException {
writer.close();
}
}
测试:
String str = "中文啊aaa111@ ";
String fileName = "F:\\dev_test\\log\\test2\\logtest.log";
MyFileWriter out = new MyFileWriter(new File(fileName));
out.setFileSize(1, MyFileWriter.TYPE_MB);// 1MB
for (int i = 0; i < 10000000; i++) {
out.write(str);
}
out.close();
String fileName = "F:\\dev_test\\log\\test2\\logtest.log";
MyFileWriter out = new MyFileWriter(new File(fileName));
out.setFileSize(1, MyFileWriter.TYPE_MB);// 1MB
for (int i = 0; i < 10000000; i++) {
out.write(str);
}
out.close();
输出:
2009-04-16 23:00 1,048,572 logtest.log
2009-04-16 23:00 1,048,610 logtest.log.1
2009-04-16 23:00 1,048,610 logtest.log.2
2009-04-16 23:00 654,208 logtest.log.3
2009-04-16 23:00 1,048,610 logtest.log.1
2009-04-16 23:00 1,048,610 logtest.log.2
2009-04-16 23:00 654,208 logtest.log.3
基本实现了每个文件都按1MB的大小输出。
转载于:https://blog.51cto.com/kinkding/150474