Skip to content

Instantly share code, notes, and snippets.

@oksep
Last active May 12, 2016 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oksep/b2444eeb1be2c9baa63aafb3aca238a9 to your computer and use it in GitHub Desktop.
Save oksep/b2444eeb1be2c9baa63aafb3aca238a9 to your computer and use it in GitHub Desktop.
Custom Log Util
package cn.septenary;
import java.util.Locale;
public class MyLog {
// adb shell setprop log.tag.MyLog VERBOSE
public static String TAG = "MyLog";
public static boolean DEBUG;
static {
DEBUG = android.util.Log.isLoggable("MyLog", android.util.Log.VERBOSE);
}
public MyLog() {
}
public static void setTag(String tag) {
d("Changing log tag to %s", new Object[]{tag});
TAG = tag;
DEBUG = android.util.Log.isLoggable(TAG, android.util.Log.VERBOSE);
}
public static void v(String format, Object... args) {
if (DEBUG) {
android.util.Log.v(TAG, buildMessage(format, args));
}
}
public static void d(String format, Object... args) {
if (DEBUG) {
android.util.Log.d(TAG, buildMessage(format, args));
}
}
public static void e(String format, Object... args) {
if (DEBUG) {
android.util.Log.e(TAG, buildMessage(format, args));
}
}
public static void e(Throwable tr, String format, Object... args) {
if (DEBUG) {
android.util.Log.e(TAG, buildMessage(format, args), tr);
}
}
public static void wtf(String format, Object... args) {
if (DEBUG) {
android.util.Log.wtf(TAG, buildMessage(format, args));
}
}
public static void wtf(Throwable tr, String format, Object... args) {
if (DEBUG) {
android.util.Log.wtf(TAG, buildMessage(format, args), tr);
}
}
private static String buildMessage(String format, Object... args) {
String msg = args == null ? format : String.format(Locale.US, format, args);
StackTraceElement[] trace = (new Throwable()).fillInStackTrace().getStackTrace();
String caller = "<unknown>";
for (int i = 2; i < trace.length; ++i) {
Class clazz = trace[i].getClass();
if (!clazz.equals(MyLog.class)) {
String callingClass = trace[i].getClassName();
callingClass = callingClass.substring(callingClass.lastIndexOf(46) + 1);
callingClass = callingClass.substring(callingClass.lastIndexOf(36) + 1);
caller = callingClass + "." + trace[i].getMethodName();
break;
}
}
return String.format(Locale.US, "[%d] %s: %s", new Object[]{Long.valueOf(Thread.currentThread().getId()), caller, msg});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment