import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.log4j.Logger;
/**
* 日志输出工具
* Created by Nemo on 2017/6/12.
*/
public class LogUtils {
private static Logger log = Logger.getLogger(LogUtils.class);
/**
* 打印警告
*
* @param obj
*/
public static void warn(Object obj) {
try{
StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
String text = getMsg(obj,stacks,"警告");
log.warn(text);
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 打印信息
*
* @param obj
*/
public static void info(Object obj) {
try{
StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
String text = getMsg(obj,stacks,"信息");
log.info(text);
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 调试信息
*
* @param obj
*/
public static void debug(Object obj) {
try{
StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
String text = getMsg(obj,stacks,"调试");
log.debug(text);
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 打印错误
*
* @param obj
*/
public static void error(Object obj) {
try{
StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
String text = getMsg(obj,stacks,"错误");
log.error(text);
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 处理信息
* @param obj
* @return
*/
private static String dealMsg(Object obj){
/*** 是否是异常 ***/
if (obj instanceof Exception) {
Exception e = (Exception) obj;
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
return sw.toString();
} else {
return obj.toString();
}
}
/**
* 得到需要打印的信息
* @param obj
* @param stacks
* @param level
* @return
*/
private static String getMsg(Object obj,StackTraceElement[] stacks,String level){
String text = "\r\n"
+ "################################\r\n"
+ "日志级别:【"+level+"】\r\n"
+ "类:【"+stacks[2].getClassName() + "】\r\n"
+ "方法:【" + stacks[2].getMethodName() + "】\r\n"
+ "行:【" + stacks[2].getLineNumber() + "】\r\n"
+ "信息:【" + dealMsg(obj) + "】\r\n"
+ "################################";
return text;
}
/**
* 向数据库告警表中插入信息
* @param obj
*/
public static void dbWarn(Object obj) {
try{
String printInfo = "";
/*** 获取输出信息的代码的位置 ***/
String location = "";
StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
location = stacks[2].getClassName() + "." + stacks[2].getMethodName()
+ "(" + stacks[2].getLineNumber() + ")";
/*** 是否是异常 ***/
if (obj instanceof Exception) {
Exception e = (Exception) obj;
printInfo = location + e.getMessage();
log.fatal(printInfo.substring(0, printInfo.length() > 512?512:printInfo.length()));
} else {
printInfo = location + obj.toString();
log.fatal(printInfo.substring(0, printInfo.length() > 512?512:printInfo.length()));
}
}catch (Exception e) {
e.printStackTrace();
}
}
}