自己动手实现一个轻量极log

[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();
}

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值