50,527
社区成员
发帖
与我相关
我的任务
分享
public class MyLog {
private final String defaultPath = "log";//默认日志存放目录
private final long length = 3 * 1024 * 1024;//单个日志文件大小
private static MyLog instance = null;
private String path;//日志存放目录
private Class clazz;
private boolean flag;//启动日志开关
private File file;
private MyLog() {
createFile();
setFlag(true);
}
public static MyLog getInstance(Class clazz) {
if (instance == null) {
instance = new MyLog();
}
instance.setClazz(clazz);
return instance;
}
public void writeLog(Object obj) {
if (flag) {
try {
FileWriter fw = new FileWriter(file, true);
PrintWriter pw = new PrintWriter(fw);
pw.println(currentTime() + "\t\tclass(" + getClazz().getName() + ")");
pw.println(obj);
pw.println();
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void writeLog(String methodName, Object obj) {
if (flag) {
try {
FileWriter fw = new FileWriter(file, true);
PrintWriter pw = new PrintWriter(fw);
pw.println(currentTime() + "\t\tclass(" + getClazz().getName() + ")\t\tmethod(" + methodName + ")");
pw.println(obj);
pw.println();
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void createFile() {
File directory = new File(getPath());
if (!directory.exists()) {
directory.mkdirs();
}
int i = 1;
long len = 0;
File tempFile = null;
while (true) {
tempFile = new File(getPath() + "\\log_" + today() + "_" + i + ".txt");
if (tempFile.exists()) {
i++;
} else if (i > 1) {
File f = new File(getPath() + "\\log_" + today() + "_" + (i - 1) + ".txt");
if (f.length() < length) {
setFile(f);
return;
}
setFile(tempFile);
return;
} else {
setFile(tempFile);
return;
}
}
}
private String today() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
return sdf.format(date);
}
private String currentTime() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
private String getPath() {
if (path == null || path.trim().equals("")) {
return defaultPath;
}
return path;
}
public void setPath(String path) {
this.path = path;
}
private Class getClazz() {
return clazz;
}
private void setClazz(Class clazz) {
this.clazz = clazz;
}
private File getFile() {
return file;
}
private void setFile(File file) {
this.file = file;
}
private boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
pw.println(currentTime() + "\t\tclass( " + getClazz().getName() + ")\t\tmethod( " + methodName + ") ");
5 多线程高并发下,你的类的设计,存在严重问题。
pw.print(currentTime());
pw.print("\t\tclass( ");
pw.print(getClazz().getName());
// ... 以此类推,并且,这个Writer最好能让用户选择是否用Buffer