Why should we log with Interceptors

Logging is a common practice that should be done in every Project. It definitely is also a cross cutting concern, which means that the same code has to be placed on different parts of the code.  Because we dont want to write the same code again and again (D(ont(R(repeat)Y(ourself) we have to find another way to log our events without having to write the same code for every class and method.

public class someClassX{
Logger logger = LoggerFactory.getLogger(someClassX);
public void doSomeX{
logger.info("Method Called: doSomeX");
}
}
public class someClassY{
Logger logger = LoggerFactory.getLogger(someClassY);
public void doSomeY{
logger.info("Method Called: doSomeY");
}
}

The solution to this problem are Interceptors.

Why should i use an Interceptor for logging

An Interceptor is feature of Java EE which is perfect for adressing cross cutting concerns. This is where Java offers a bit of aspect oriented programming. But what exaclty does this mean?

@Interceptor
public class RestLogger {
@AroundInvoke
public Object collectBasicLoggingInformation(InvocationContext context) throws Exception{
Logger logger = LoggerFactory.getLogger(context.getClass());
logger.info("Method Called: " + context.getMethod().getName());
logger.info("Parameters: " + context.getParameters().toString());
return context.proceed();
}
}

There are a few things a class needs to be a valid Interceptor

  • @Interceptor annotation at class level
  • method with @AroundInvoke annotation
  • this method needs to return Object /InvocationContext  as parameter/ throw Exception
  • context.proceed() otherwise the caller of the interceptor would never run again

The Interceptor is now ready to rock.

Logging done right

Now we can use the Inceptor.

@Interceptors(RestLogger.class)
public class someClassX{
public void doSomeX{
}
}
public class someClassY{
@Interceptors(RestLogger.class)
public void doSomeY{
}
}

Just by annotating the class with our Interceptor every Method in the class will be logged. Or choose to go on method level to have a greater flexibility what you want to log. Method Level Interceptors are always be preferred when there is also a Class Level one.

If you want to see a more detailed example make sure to check out this porject on my github account

https://github.com/CanGue/WeatherRest

 

Spread the love