akka/akka-http

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

開放

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

 (2 則留言) (0 個反應) (0 位負責人)Scala (598 個分叉)batch import
1 - triagedhelp wantedt:docs

倉庫指標

星標
 (1,311 顆星)
PR 合併指標
 (平均合併 1天 10小時) (30 天內合併 2 個 PR)

描述

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.

貢獻者指南