When analyzing the cause of a program error, it is useful to understand its state of the day. In many cases, we can do this through a stack trace, but this information is often unavailable, or you may need information about the program's handling of the data in case of an error.
The traditional approach is to use a record framework such as the log4j and Java Logging APIs, and then manually write and maintain the required record statements. This is a tedious and error-prone operation and is generally suitable for automatic implementation. Java 5 added Java instrumentation mechanism allows you to examine and modify the loaded class byte code by providing a "Java proxy".
This article shows you how to implement this Java proxy, which transparently adds entry and exit records to all methods in a class with the standard Java Logging API. Take Hello world for example:
public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
The following is the same use case where the entry and exit record statements are added:
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LoggingHelloWorld {
final static Logger _log = Logger.getLogger(LoggingHelloWorld.class.getName());
public static void main(String args[]) {
if (_log.isLoggable(Level.INFO)) {
_log.info("> main(args=" + Arrays.asList(args) + ")");
}
System.out.println("Hello World");
if (_log.isLoggable(Level.INFO)) {
_log.info("< main()");
}
}
}