您的位置:首页 > 其它

Logger-功能强大使用方便的Log日志打印工具类

2016-05-17 19:41 591 查看

介绍

Android开发中Log日志打印对开发者来说是非常重要的功能。但是感觉Log写多了也是烦,每次都需要设置一个TAG过滤值和具体的打印信息,而且打印的信息也不够丰富。

这里我推荐一个功能强大的Log日志打印工具类-Logger。(不是java.util.logging.Logger,只是恰好同名而已)

使用

使用非常简单,直接调用静态类方法。提供Debug/Info/Error三个级别的打印方法。每个方法又分为两种,有参数和空参的两种。

Logger.d();
Logger.d("log message");


使用效果

有图为证。打印效果,格式说明。

默认TAG: [ 执行类:调用的方法:代码行数 ] :打印信息



打出的信息非常丰富,有方法和代码行数。方便我们定位代码。还可以在版本发布后,统一关闭日志打印功能。很好的满足了我们的开发日志打印功能。

源码及说明

代码说明

TAG在工具类中设置好,每个App项目都有特定的TAG。

设计3个布尔值,作为用来控制打印的开关,默认ture。在版本发布后改为false就好了。

每个打印,都有两个重载方法,有参无参,根据实际情况使用。

最后getLocation方法,获取堆栈信息,提供打印方法和代码行功能。

源码

public final class Logger {

private static final String TAG = "Demo";

/**
* Set true or false if you want read logs or not
*/
private static boolean logEnabled_d = true;
private static boolean logEnabled_i = true;
private static boolean logEnabled_e = true;

public static void d() {
if (logEnabled_d) {
android.util.Log.d(TAG, getLocation());
}
}

public static void d(String msg) {
if (logEnabled_d) {
android.util.Log.d(TAG, getLocation() + msg);
}
}

public static void i(String msg) {
if (logEnabled_i) {
android.util.Log.i(TAG, getLocation() + msg);
}
}

public static void i() {
if (logEnabled_i) {
android.util.Log.i(TAG, getLocation());
}
}

public static void e(String msg) {
if (logEnabled_e) {
android.util.Log.e(TAG, getLocation() + msg);
}
}

public static void e(String msg, Throwable e) {
if (logEnabled_e) {
android.util.Log.e(TAG, getLocation() + msg, e);
}
}

public static void e(Throwable e) {
if (logEnabled_e) {
android.util.Log.e(TAG, getLocation(), e);
}
}

public static void e() {
if (logEnabled_e) {
android.util.Log.e(TAG, getLocation());
}
}

private static String getLocation() {
final String className = Logger.class.getName();
final StackTraceElement[] traces = Thread.currentThread()
.getStackTrace();

boolean found = false;

for (StackTraceElement trace : traces) {
try {
if (found) {
if (!trace.getClassName().startsWith(className)) {
Class<?> clazz = Class.forName(trace.getClassName());
return "[" + getClassName(clazz) + ":"
+ trace.getMethodName() + ":"
+ trace.getLineNumber() + "]: ";
}
} else if (trace.getClassName().startsWith(className)) {
found = true;
}
} catch (ClassNotFoundException ignored) {
}
}

return "[]: ";
}

private static String getClassName(Class<?> clazz) {
if (clazz != null) {
if (!TextUtils.isEmpty(clazz.getSimpleName())) {
return clazz.getSimpleName();
}

return getClassName(clazz.getEnclosingClass());
}

return "";
}

}


来源

其实这也不是我写的,只是在开发的时候发现了,分享出来。

代码来源是:Yalantis公司的开源项目中的工具类。

Yalantis公司有很多效果非常酷炫的开源项目,大家可以上github上看看。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: