Search code examples
androidlogcatandroid-log

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.


Solution

  • 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();
    
      }
    }