您的位置:首页 > 其它

模拟Log4j输出信息

2015-08-21 14:53 330 查看

模拟Log4j输出信息

一直以来都觉得system.out.print输出的信息不够详细,不能像log4j那样输出日期时间,输出的类,输出的类型等等;使用[log4j][1]虽然简单,但是在很多时候我们只需要log4j的简单的打印输出功能,所以在这里我模拟log4j,写了一个简单的工具类

public class Log {

protected Class<?> clazz = Log.class;//利用java反射得到class,继而可以得到类名
protected boolean date_type = false;//日期类型,true打印日期时间,false打印日期
protected int log_level = 1;//输出等级
//protected static int min_level = 1;//能输出的最小等级等级
//protected static int max_level = 1;//能输出的最大等级等级
public static final int LOG_LV_INFO = 3;
public static final int LOG_LV_DEBUG = 2;
public static final int LOG_LV_ERROR = 1;

public Log() {
}

public Log(Class<?> clazz) {
this.clazz = clazz;
this.date_type = false;
this.log_level = LOG_LV_INFO;
}

public Log(Class<?> clazz, boolean date_type) {
this.clazz = clazz;
this.date_type = date_type;
this.log_level = LOG_LV_INFO;
}

public Log(Class<?> clazz, boolean date_type, int LV) {
this.clazz = clazz;
this.date_type = date_type;
this.log_level = LV;
}

public void out(String msg, Exception e){
if(date_type == true) {
System.out.println("[" + Dates.currentDateTime() + "] - [Exception] - [" + clazz.getSimpleName() +"] " + msg + " : " + e.getMessage());
} else {
System.out.println("[" + Dates.currentDate() + "] - [Exception] - [" + clazz.getSimpleName() +"] " + msg + " : " + e.getMessage());
}
e.printStackTrace();
}

public /*synchronized*/ void out(String str) {
String outStr;
if(date_type == true) {
outStr = "[" + Dates.currentDateTime() + "]-";
} else {
outStr = "[" + Dates.currentDate() + "]-";
}
outStr += "[" + clazz.getSimpleName() + "]-";
switch (log_level) {
case 3:
outStr += "[info]-";break;
case 2:
outStr += "[debug]-";break;
case 1:
outStr += "[error]-";break;
default:
break;
}
outStr +=  "[" + Thread.currentThread().getName() + "] " + str;
System.out.println(outStr);
}

/**
* <p>模拟log4j对象映射输出</p>
* 通过匹配{},映射传入的每个对象<br>
* 知识点:Object...obj 该用法是JDK1.7的新特性,可以传入多个不同类型的对象
* <pre>
* log.out("A={},B={}{}","a","b",e,1,111)
*      = ... A={a},B={b}{Exception} 1 111
* </pre
*/
public /*synchronized*/ void out(String str, Object...obj) {
for (int i = 0; i < obj.length; i++) {
if(null != obj[i]){
if(str.contains("{}")){
int begin_index = str.indexOf("{}");
str = str.substring(0, begin_index + 1) + obj[i].toString() + str.substring(begin_index + 1, str.length());
} else {
str += " " + obj[i].toString();
}
}
}
out(str);
}


其中的Dates是我自己写的时间工具类,下面是使用方法,和log4j很相似

public class Test {

private static final Log log = new Log(Test.class,false,Log.LOG_LV_DEBUG);

public static void main(String[] args) {
Log logger = new Log(Test.class);
logger.out("123");
log.out("A={},B={},C={}{}","a","b","c",1,2);
}


输出结果是:

[2015-08-21]-[Test]-[info]-[main] 123

[2015-08-21]-[Test]-[debug]-[main] A={a},B={b},C={c}{1} 2

当然也可以模拟log4j,通过properties配置文件获取date_type,log_level等属性,也可以利用IO输出成log文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: