I am creating a Quarkus web application with Jakarta EE. I have some @GET
and @POST
methods and I want to log their usage. For this I am using an interceptor like this:
@Loggable
@Interceptor
@Priority(1)
public class Logger {
@Inject
private LogService logService;
@AroundInvoke
public Object logMethodEntry(InvocationContext context) throws Exception {
Date currentDateAndTime = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String dateAndTime = dateFormat.format(currentDateAndTime);
String methodName = context.getTarget().getClass().getName() + "." + context.getMethod().getName();
String ipAddress = "";
Log log = new Log(dateAndTime, ipAddress, methodName);
logService.addLog(log);
return context.proceed();
}
}
This interceptor is using @Loggable
to be registered to the target class. My question is ,how can I retrieve the client IP address? I tried using HttpServletRequest
but I am getting dependency compile errors.
NOTE: This is being used only on @GET
and @POST
methods, so there is always an HTTP request.
I have figured it out, you cannot use HttpServletRequest
for this since there are dependency errors. You can just use IP grabbing external REST API and call it from the interceptor, since calling the method from the interceptor is the same as calling it from JAX-RS resource method.