Logging method execution in Java 17

AspectJ maven plugin allows logging execution of any selected methods without changes in the application code. The plugin still does not support Java 17, one has to use its alternative.

Marian Čaikovski

--

Detailed logs can be helpful for debugging or performance monitoring. If you want to log execution of many methods, you do not need to pollute those methods with calls to a logger. Without changing the application code you can log any method name, its arguments, return value and execution time.

To log methods, you have to add to the application a custom dependency and compile the application with the AspectJ maven plugin. The depency provides signatures of the methods to be intercepted together with code that will call a logger. I demonstrated this simple approach in an earlier post. Unfortunately, like some useful libraries, the super useful AspectJ maven plugin also does not support Java 17. Fortunately, it can be replaced its less famous analog sharing the same name.

To demonstrate that the plugin nicely works with Java 17, I use a simple Spring Boot-based web application. I use Spring Boot because it allows creating web applications as standalone jars.

The demo application serves a typical task — it saves objects received from a browser into a database, and displays in the browser the previously saved items. The sample web interface is ugly and primitive but sufficient for demonstrating logging of the backend methods. When the only button Post item is pressed, a new sample object is saved into the database and then all the saved objects are loaded from the database and displayed in the browser.

The posted object contains only two fields — a description set by the browser and an id generated in the database:

@Entity
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
String description;
}

--

--

Marian Čaikovski

Java, JavaScript and SQL developer. Interested in data collection and visualization.