Convenience method for writing information to the logcat - Android App

Android examples for App:Log

Description

Convenience method for writing information to the logcat

Demo Code

/*//  ww  w.ja va2s . co m
 * Copyright 2013 Phil Brown

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
//package com.book2s;
import java.lang.reflect.Method;
import java.util.Locale;

import android.util.Log;

public class Main {
    /**
     * Convenience method for writing information to the logcat
     * @param information
     * @param args
     */
    public static void info(String information, Object... args) {
        try {
            Method m = Log.class.getMethod("i", new Class<?>[] {
                    String.class, String.class });
            log(m, information, args);
        } catch (Exception e) {
            Log.w("AbLE", "Log Failed", e);
        }
    }

    /**
     * Convenience method for writing a verbose message to the logcat
     * @param verbose
     * @param args
     */
    public static void log(String verbose, Object... args) {
        try {
            Method m = Log.class.getMethod("v", new Class<?>[] {
                    String.class, String.class });
            log(m, verbose, args);
        } catch (Exception e) {
            Log.w("AbLE", "Log Failed", e);
        }
    }

    /**
     * This method is used by the core logging functions to nicely format output to the logcat
     * @param logMethod the method to call. Should be {@link Log#i(String, String)} or another {@link Log} static method
     * @param format the text to display, using java string format arguments
     * @param args the arguments to show in the format string.
     */
    private static void log(Method logMethod, String format, Object... args) {
        try {
            StackTraceElement[] trace = Thread.currentThread()
                    .getStackTrace();
            StringBuilder b = new StringBuilder();
            b.append(format).append(", ");
            int index = 1;
            String name = null;
            boolean loop = true;
            do {
                index++;
                if (trace != null && index < trace.length) {
                    name = trace[index].getClassName();

                    if (name != null) {
                        if (!name.contains("self.philbrown.AbLE.AbLEUtil")) {
                            loop = false;
                        }
                    }
                } else {
                    index = 1;
                    loop = false;
                }

            } while (loop);
            b.append(formatStackTrace(trace[index]));
            b.append(buildCommaSeparatedString(args));
            try {
                logMethod.invoke(null, "AbLE",
                        String.format(Locale.US, b.toString(), args));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Throwable t) {
            Log.w("AbLE", "Log Failed", t);
        }
    }

    /**
     * Formats a stack trace into a single line that provides relevant information for debugging
     * @param element the element to format
     * @return a well-formatted stack-trace line containing the class name, method name, and line number
     * that, when clicked in the logcat, will display the line or source from where the message originated.
     */
    public static String formatStackTrace(StackTraceElement element) {
        StringBuilder b = new StringBuilder();

        b.append(" at ");
        String clazz = element.getClassName();
        b.append(clazz).append(".");
        b.append(element.getMethodName()).append("(");
        b.append(clazz.substring(clazz.lastIndexOf(".") + 1)).append(
                ".java:");
        b.append(element.getLineNumber()).append(")").append(" , ##");
        return b.toString();
    }

    /**
     * Takes a list of Objects and calls their {@link #toString()} methods to get their string representation, then
     * inserts a comma between all of them
     * @param args a list of Objects to get as a comma-separated list 
     * @return a comma-separated list of the given {@code args}
     */
    public static String buildCommaSeparatedString(Object... args) {
        if (args == null)
            return "";
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < args.length; i++) {
            b.append(args[i]);
            if (i != args.length - 1) {
                b.append(", ");
            }
        }
        return b.toString();
    }

    /**
     * Handles String format for the default (US) Locale. This should be used for locale-agnostic
     * messages to prevent locale errors, such as commas used instead of decimals.
     * @param format
     * @param args
     * @return
     */
    public static String format(String format, Object... args) {
        return String.format(Locale.US, format, args);
    }
}

Related Tutorials