Java - Redirect library logs to application's destination

     Application developers would often like to view the logs of dependency library (jars) in sequence to that of application logs and having the library's log redirected to the same destination (files, console, logcat etc) as that of the appplication's log helps achieve sequenced logs and isolate root cause among library and applications. Java's java.util.logging.Logger helps in quick implementation of the need,

Library:

   The sample library has two components and lets applications control the logs of whichever component is needed.

// Class Focus's code

public static String FOCUS_COMPONENT_NAME = "com.android.camera.focus";
Logger componentLogger = Logger.getLogger(FOCUS_COMPONENT_NAME);
componentLogger.setUseParentHandlers(false);
Logger libraryLogger = componentLogger.getParent();



// Class Zoom's code


public static String ZOOM_COMPONENT_NAME = "com.android.camera.zoom";
Logger componentLogger = Logger.getLogger(ZOOM_COMPONENT_NAME);
componentLogger.setUseParentHandlers(false);
Logger libraryLogger = componentLogger.getParent();



// Common Logging function in library



void Log(Level level, String message) {
    libraryLogger.log(level, message);
    componentLogger.log(level, message);
}


componentLogger redirects logs to applications which specify the exact component name like (com.android.camera.zoom or com.android.camera.focus) libraryLogger redirects logs to applications which specify a part of the component name like (com or com.android or com.android.camera)

Application:

    Application needs to setup a handler to receive the logs redirected from the library.

// Disable root logger's ConsoleHandler (System.err)
LogManager.getLogManager().reset();

// Specify the component name to control library logs
Logger logger = Logger.getLogger("com.android.camera");

Handler handler = new Handler() {
@Override
public void publish(LogRecord logRecord) {
   System.out.println("Thread [" + Thread.currentThread().getId() + "] " +
   logRecord.getSourceClassName() + " : " + logRecord.getMessage());
}

@Override
public void flush() {
   System.out.flush();
}
};

logger.addHandler(handler);

Applications can control the redirected logs from library.

Disable all logs redirected from library

// void or any string which doesn't match with that of the library
Logger.getLogger("void");

Enable all logs redirected from library

Logger.getLogger("com.android.camera");
or
Logger.getLogger("com.android");
or
Logger.getLogger("com");

Enable logs of specific component of the library

Logger.getLogger("com.android.camera.focus");
or
Logger.getLogger("com.android.camera.zoom");

Control the logging level of the library

logger.setLevel(Level.ALL);
or
logger.setLevel(Level.OFF);

No comments: