akka/akka-http

Describe on how a logger can be customised in the Route-Chain (Java) / modify MDC

Open

#3,378 建立於 2020年7月20日

在 GitHub 查看
 (2 留言) (0 反應) (0 負責人)Scala (1,311 star) (598 fork)batch import
1 - triagedhelp wantedt:docs

描述

I need to customise the logger that gets returned by extractLog( log -> () ) so I can attach the current correlationId / userId / other fields into the MDC. However, I'm unable to accomplish this with the documentation I found. This is what I got so far:

  public static RouteAdapter extractCorrelationId(Function<String, Route> inner) {
    return optionalHeaderValueByName("X-CorrelationId", (corr) -> extractLog(log -> {
      String correlationId = corr.orElseGet(() -> {
        String c = UUID.randomUUID().toString();
        log.debug("request does not have a upstream correlationId, assigning " + c);
        return c;
      });
      return provide(correlationId, inner);
    }));
  }

and I was planning to decorate my root-route as follows:

  public Route createRoute() {
    return extractCorrelationId(corr -> extractLog(log -> {
      LoggingAdapter newLog = log;
      var newMDC = newLog.mdc().$plus(Tuple2.apply("correlationId", corr)); // this is a MDC and not a LoggingAdapter :( 
      // how to bring the newMDC into the newLog ?  because AFAIK the MDC is a immutable list, thus I cannot simply change its values 
      return withLog(newLog, () -> allRoutes());
    }));
  }

Please provide a way on how a valid "LoggingAdapter" can be constructed from Java.

貢獻者指南