Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I monitor android.util.log or override it?

I'm using log.d/v/w/e everywhere in the project.

Now, I want to save all the logs to the device local file.

However, the android.util.Log class in the final class.

That means I can't extend from it.

Is there a way to take over control for android.util.Log, so that I don't need to change log.d/v/w/e everywhere in the project?

I'm looking for a simple way to know if log.d/v/w/e is getting called and so that I can write the info to the local file.

like image 838
CodingTT Avatar asked Oct 29 '25 07:10

CodingTT


2 Answers

When you need to add to the functionality of a final class, a common option is to use the decorator (wrapper) pattern:

public class LogUtils {

  public static void LOGE(String tag, String message) {
     Log.e(tag, message);
     doSomethingElse();
  }

  ...
}

This sort of implementation for logging is pretty popular.

However, there's another option to writing your own wrapper. Jake Wharton's library Timber already handles all the utility, and adds some other niceties like automatic tags and use of String.format for Java.

You can add your own functionality to handle your own diagnostic logic kind of like so:

public class MyLoggingClass extends DebugTree {

  @Override
  public void log(int priority, String tag, String message, Throwable t) {

    if (BuildConfig.DEBUG) {
       super.log(priority, tag, message, t);
    }

    doSomethingElse();

  }
}
like image 71
RBusarow Avatar answered Oct 31 '25 08:10

RBusarow


Remove any 'import android.util.Log' from a file and you can include your own log class:

// log.java
package com.my.package;

public class Log {
    public static int v(String tag, String msg) { return println(android.util.Log.VERBOSE, tag, msg); }
    public static int d(String tag, String msg) { return println(android.util.Log.DEBUG,   tag, msg); }
    public static int i(String tag, String msg) { return println(android.util.Log.INFO,    tag, msg); }
    public static int w(String tag, String msg) { return println(android.util.Log.WARN,    tag, msg); }
    public static int e(String tag, String msg) { return println(android.util.Log.ERROR,   tag, msg); }

    public static int println(int priority, String tag, String msg)  {
        // Do another thing
        return android.util.Log.println(priority, tag, msg);
    }
}

Then you can leave all your 'Log.e' lines undisturbed, but still intercept the logging lines.

This isn't a complete replacement/implementation of the android.util.Log class, but it's got all the functions I use and it's easy to extend if you need to.

like image 39
Andy Krouwel Avatar answered Oct 31 '25 07:10

Andy Krouwel