日誌記錄工具類
阿新 • • 發佈:2019-02-03
import org.apache.log4j.Logger;
public class LogUnits {
private static Logger logger = null;
public static void logException(Exception e){
StackTraceElement[] stacks = (new Throwable()).getStackTrace();
String newClass = stacks[1].getClassName();
if(logger == null || !newClass.equals(logger.getName())){
logger = Logger.getLogger(newClass);
}
StringBuffer logInfo = new StringBuffer(100);
logInfo.append("Exception happen in Method:" + stacks[1].getMethodName()+"();");
logInfo.append("\r\n");
logInfo.append(" line number:"+stacks[1].getLineNumber()+ ";");
logInfo.append("\r\n");
StringWriter trace = new StringWriter();
e.printStackTrace(new PrintWriter(trace));
logInfo.append(" Exception:");
logInfo.append(trace.toString()); logger.error(logInfo.toString());
}
public static void logInfo(String message){
StackTraceElement[] stacks = (new Throwable()).getStackTrace();
String newClass = stacks[1].getClassName();
if(logger == null || !newClass.equals(logger.getName())){
logger = Logger.getLogger(newClass);
}
StringBuffer logInfo = new StringBuffer(100);
logInfo.append("Method Name:" + stacks[1].getMethodName()+"();");
logInfo.append("\r\n");
logInfo.append("line number:"+stacks[1].getLineNumber()+ ";");
logInfo.append("\r\n");
logInfo.append("Message:");
logInfo.append(message);
logger.info(logInfo);
}
public static void logDebug(String message){
StackTraceElement[] stacks = (new Throwable()).getStackTrace();
String newClass = stacks[1].getClassName();
if(logger == null || !newClass.equals(logger.getName())){
logger = Logger.getLogger(newClass);
}
StringBuffer logInfo = new StringBuffer(100);
logInfo.append("Method Name:" + stacks[1].getMethodName()+"();");
logInfo.append("\r\n");
logInfo.append("line number:"+stacks[1].getLineNumber()+ ";");
logInfo.append("\r\n");
logInfo.append("Message:");
logInfo.append(message);
logger.debug(logInfo);
}
}