Skip to content
Advertisement

Design pattern for logging entry and exit of methods?

I have an overall design and architecture question. After looking at design patterns (decorators, chain of commands, and so on) it is still unclear to me.

Requirement: I would like to have logging for both entry and exit of my methods.

As of now, all my methods looks like:

JavaScript

(Below the logging, I am also using some KPI library to send some timestamp, like StatsD)

All structures are really of the form:

JavaScript

Now, looking at my project, I have some 290 methods who are following the EXACT same structure.

Is there a clever way of resolving this? Maybe with a nice pattern? Some annotations? Aspects? I am open to suggestion as I believe there is definitely a better solution than my current one.

Advertisement

Answer

A possible solution is using your dependency injector + annotations.

Here you have an example on how to implement what you want using Weld in a JavaSE application.

You need to add this dependency:

JavaScript

Then create an annotation that it will be use to point those methods you want to log.

JavaScript

Create the interceptor

JavaScript

As you see @AroundInvoke allows us to control when entering a method and exiting.

We have to inform Weld that there is a new Interceptor, we do so by adding beans.xml in META-INF folder.

JavaScript

Lastly we need to call our entity through Weld as it is in charge of creating and execute interceptors.

JavaScript

And you will get an output like:

JavaScript

This is project structure in case of need.

Project structure

Note: In case you are in a JavaEE project, all related to Weld creation is managed by your container.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement