自己做的一个简易日志系统,欢迎提出意见
[code=Java]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;
}
}[/code]
[解决办法]
建议你使用 log4j 或者 JDK 中自带的日志吧。你的这个在生产环境中没有使用价值。
[解决办法]
建议LZ先整理下自己的日志系统都有什么功能 再与现在已经存在的并且比较流行的日志工具相比较看看有什么没有的功能 诸如此类的 不一定要做产品 权当是自己学习了