记录到内存的Logger,可用于web动态显示内容的来源
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 一个日志工具-只记录到内存
*
* @author jeffay.jiang
*
*/
public class MemoryLogger {
public static Logger log = LoggerFactory.getLogger(MemoryLogger.class);
public static final String THIS_CLASS_NAME=MemoryLogger.class.getName();// "MemoryLogger";
public static final String TO_MSG=" >> ";
private DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS");
private PrintStream bp;
private ByteArrayOutputStream bs;
private ArrayList<String> memLog;
private int mlogSize = 500;
public MemoryLogger() {
this(500);
}
public ArrayList<String> getLogMsg() {
return memLog;
}
public MemoryLogger(int size) {
memLog = new ArrayList<String>();
mlogSize = size;
}
public void log(String msg) {
String caller = "";
StackTraceElement stack[] = Thread.currentThread().getStackTrace();
for ( int i=0; i<stack.length; i++ ) {
if ((stack[i].getClassName().indexOf(THIS_CLASS_NAME))>=0 ) {
if(i+1<stack.length){
caller=stack[i+1].getClassName() + "."+ stack[i+1].getMethodName();
}
}
}
String d = df.format(new Date());
log.info(caller+TO_MSG+msg);
memLog.add(0, d+" "+caller+TO_MSG+msg);
if (memLog.size() > mlogSize) {
memLog.remove(mlogSize);
}
}
public void log(Exception e) {
String caller = "";
StackTraceElement stack[] = Thread.currentThread().getStackTrace();
for ( int i=0; i<stack.length; i++ ) {
if ((stack[i].getClassName().indexOf(THIS_CLASS_NAME))>0 ) {
if(i+1<stack.length){
caller=stack[i+1].getClassName() + "."+ stack[i+1].getMethodName();
}
}
}
String d = df.format(new Date());
try {
String msg=toString(e);
log.info(caller+TO_MSG+msg);
memLog.add(0, d+" "+caller+TO_MSG+msg);
if (memLog.size() > mlogSize) {
memLog.remove(mlogSize);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
public synchronized String toString(Exception ex) throws Exception {
if (bs == null) {
bs = new ByteArrayOutputStream();
bp = new PrintStream(bs, true, "utf-8");
}
if (ex == null) {
return "NULL";
}
bs.reset();
ex.printStackTrace(bp);
bp.flush();
byte[] b = bs.toByteArray();
String msg = new String(b, "utf-8");
return msg;
}
}