Mostrando entradas con la etiqueta log. Mostrar todas las entradas
Mostrando entradas con la etiqueta log. Mostrar todas las entradas

viernes, 11 de febrero de 2011

Android: my custom log class

I use a custom log class on all my Android projects to easy my life.

Advantages
  • Possibility to enable/disable log by configuration. Useful to keep your releases clean.
  • Class call trace. Know which class is displaying which log message with no extra text.

How it's done?

Really easy. Just create a new class:
class Log {
public final static String LOGTAG = "Phone2Chrome";
static final boolean LOGV = true;

static void v(String logMe) {
 if (LOGV) {
  try {
   throw new Exception("go go logger");
  } catch (Exception e) {
   String className = e.getStackTrace()[1].getClassName();
   className = className.substring(className.lastIndexOf(".")+1, className.length());
   android.util.Log.v(LOGTAG, className + "." + e.getStackTrace()[1].getMethodName() + "() --- " + logMe);
  }
 }
}

Import it in your Android classes and make this replacement:
void myFunction() {
- Log.d(TAG, "MyActivity - myFunction: hello logcat");
+ Log.v("hello logcat");
}

What you are going to see in logcat is something like this:

V/Phone2Chrome(16119): MyActivity.myFuntion() --- hello logcat.

No more dirty log messages anymore!