how to log with request context information in Quarkus

188 Views Asked by At

I have a Quarkus service, and would like to log with DataDog trace id for distributed tracing. The trace id is from the request header and differs per request.

In the current setup, I have singleton logger in an @ApplicationScoped bean, for example,

@ApplicationScoped
public class FooServiceImpl implements FooService {

  private static final Logger LOG = LoggerFactory.getLogger(FooServiceImpl.class);

  # error occurred, LOG.error("xxx")

How can I inject the request header and use it to enrich my log message?

1

There are 1 best solutions below

3
On
  • You can attempt to inject the HttpServerRequest bean.
import io.vertx.core.http.HttpServerRequest;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Context;
import org.jboss.logging.Logger;

@RequestScoped
public class FooServiceImpl implements FooService {

  @Inject Logger logger;
  @Context HttpServerRequest httpRequest;

  @Override
  public String foo() {
    httpRequest.headers().forEach((key, value) -> {
      logger.debug("Header: " + key + " = " + value);
    });
    return "foo";
  }
}
  • Another approach is to create a filter class that implements ContainerRequestFilter.
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import java.io.IOException;

import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;

@Provider
public class RequestFilter implements ContainerRequestFilter {
  @Inject Logger logger;

  public RequestFilter() {}

  public void filter(ContainerRequestContext containerRequestContext) throws IOException {
    containerRequestContext
        .getHeaders()
        .forEach(
            (key, value) -> {
              logger.debug("Header: " + key + " = " + value);
            });
  }
}

https://quarkus.io/guides/resteasy-reactive#request-or-response-filters