Logger class

Usage:

MyLog.d("Your log is here");

Result:

logs

Logger class:

public class MyLog {
    public static final String TAG = "ZAQ - ";

    public static void d(String msg) {
        if (MyApplication.SHOW_LOGS) {
            logIt(Log.DEBUG, msg);
        }
    }

    private static void logIt(int level, String msg) {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        if (stackTrace != null && stackTrace.length > 4) {
            StackTraceElement element = stackTrace[4];
            String fullClassName = element.getClassName();

            StringBuilder simpleClassName = new StringBuilder(
                    fullClassName.replace(MyApplication.getMyPackageName(), ""));
            while (simpleClassName.length() < 35) simpleClassName.append(" ");

            StringBuilder methodName = new StringBuilder(element.getMethodName());
            methodName.append("()");
            while (methodName.length() < 20) methodName.append(" ");

            msg = MessageFormat.format("T:{0} | {1} # {2}() => {3}", 
                     Thread.currentThread().getId(), 
                     simpleClassName, 
                     methodName, 
                     msg);
            Log.println(level, TAG, msg);
        }
    }
}

MyApplication class

public class MyApplication extends Application {
    public static final boolean SHOW_LOGS = true;
}

* don’t forget to add — android:name=”.MyApplication” — to your AndroidManifest.xml in ‘application’ tag

Inspired by: https://gist.github.com/dors/4651b8ecff2f76c012ae


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.