[b]
大家可能每天都在用apache 的log4j在打log,可大家有没想过它的内部是怎么实现的呢,我在这里实现的一个简单的log,希望对大家了解打log的过程有所了解。
由于实现的比较简单,没有加入对log level的支持。
[/b]
大家可能每天都在用apache 的log4j在打log,可大家有没想过它的内部是怎么实现的呢,我在这里实现的一个简单的log,希望对大家了解打log的过程有所了解。
由于实现的比较简单,没有加入对log level的支持。
[/b]
public class AuditLogManager {
private static LogFileThread logFile = null;
private static boolean bWrite = true;
public static void writeInfo(String sInfo) {
if (!bWrite)
return;
if (logFile == null) {
logFile = new LogFileThread();
logFile.start();
}
logFile.writeInfo(sInfo);
}
}
class LogFileThread extends Thread {
private static FileOutputStream outLogFile = null;
private static boolean bInit = false;
private static boolean bErr = false;
private static Vector vInfo = new Vector();
public LogFileThread() {
}
private void init(String fileName) {
try {
if (bInit)
return;
String logFile = "c:/worksapce/log";
File f = new File(logFile);
f.mkdirs();
logFile += "/AuditLog_" + fileName + ".log";
outLogFile = new FileOutputStream(logFile, true);
} catch (Exception e) {
bErr = true;
e.printStackTrace();
}
bInit = true;
}
public void writeInfo(String info) {
if (info == null)
return;
procInfo(info, true);
}
private String getInfo() {
return procInfo(null, false);
}
private synchronized static String procInfo(
String info,
boolean bPutInfo) {
if (bErr) {
vInfo.clear();
return null;
}
String sInfo = null;
try {
if (bPutInfo) {
if (info != null)
vInfo.add(info);
} else {
if (vInfo.size() > 0) {
sInfo = (String) vInfo.get(0);
vInfo.remove(0);
}
}
} catch (Exception e) {
bErr = true;
e.printStackTrace();
}
return sInfo;
}
private void writeFile(String info) {
try {
if (info == null)
return;
outLogFile.write(info.getBytes());
} catch (Exception e) {
bErr = true;
e.printStackTrace();
}
}
private void close() {
try {
bInit = false;
bErr = false;
if (outLogFile != null)
outLogFile.close();
outLogFile = null;
} catch (Exception e) {
e.printStackTrace();
}
bInit = false;
}
public void run() {
try {
String oldDate = null;
while (true) {
String curDate = DateTime.getCurrentDate(0);
if (oldDate == null || !oldDate.equalsIgnoreCase(curDate)) {
oldDate = curDate;
close();
init(oldDate);
}
String curTime = DateTime.getCurrentTimestamp(0);
String ss = formatInfo(curTime);
writeFile(ss);
if (ss == null)
sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String formatInfo(String time) {
String sInfo = procInfo(null, false);
if (sInfo == null)
return null;
String sh = "*******" + time + "*******\r\n\r\n";
sh += sInfo;
sh += "\r\n\r\n******* End *******\r\n\r\n";
return sh;
}
protected void finalize() {
try {
System.out.println("Close Log Manager");
this.interrupt();
outLogFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}