My application has several JAX-RS
API, all of them are getting a transaction id as header, is there way we can access transaction id into Jboss Logger
? we tried MDC
but does that not help. Basically I am looking efficient way to add transaction id into each log.
You did not mention how you actually do the logging: explicit log.
statements in the code, or some CDI/JAXRS interceptors...
A common way to achieve the desired functionality is to define a filter/interceptor on the boundary layer (JAX-RS in your case), that extracts the relevant request data and stores it in a context thats available to logger during execution of that request. Which is exactly what JAX-RS filters and MDC are for.
A simple example:
@Provider
public class TransactionLoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {
@Context
HttpServerRequest request;
@Override
public void filter(ContainerRequestContext context) {
MDC.put("transactionId", request.getHeader("transactionId"));
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
MDC.remove("transactionId");
}
}
With that, you will store the value of your transactionId
header in MDC scope before each HTTP request is processed and remove it after processing is complete.
Note: if you have other JAX-RS filters, you might need to configure priorities correctly (so that your logging extraction filter runs before others for example) see documentation
MDC scope is bound the thread that executes the request(careful if you use Quarkus reactive, make sure that it is propagated correctly) and will be passed to the logger impl with every log invocation.
To actually print out the value from MDC in your logs, you need to modify the Quarkus log format via:
quarkus.log.console.format=%d{HH:mm:ss} %-5p %X{transactionId} [%c{2.}] (%t) %s%e%n
You can access any MDC scope var with expression %X{var_name}
.
See Quarkus documentation on logging for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With