1

In my spring-boot java project, I have hundreds of API which call other backend API on different cases. These calls happen in parallel threads (inside CompletableFuture async methods). For logging purpose, I need to log each calls with an unique ID for a single session, to identify which backend call got initiated for which session. Note that multiple sessions run in parallel as well. (Logging mechanism is not my concern here.)

Suppose: a user, using my Module, requested some data. This is a "session" in my API. My module will now automatically assign an unique ID (let's call this "UID") to this session. Now, suppose 15 different requests were executed in CompletableFuture parallel threads to retrieve data from backend servers for this user request. I need logs for each of these calls which will include this UID in them.

For making this UID available globally for logging mechanism, in the begin of a session (Spring API controller layer) I used MDC (Mapped Diagnostic Context) and put this value using

MDC.put("uid", uid);

Now, whenever an async call happens in some class, I need to put this value in MDC like above to make it available in the new thread as well like the following:

String uid = MDC.get("uid")
CompletableFuture.supplyAsync({
    MDC.put("uid", uid)
    ...  //some api related tasks

While this approach works, it is also troublesome as I need to manually add this line inside every single async calls. This results in time wasting, editing codes complicated, making future changes troublesome and also I need to put a lot of effort.

So, I need to set something like pointcut in aspect oriented programming where I will define this to put value in MDC after any CompletableFuture async method call instead of manually adding the above line in each case, if it is possible in some way.

Any ideas?

  • Thinking out loud, do you have a context you can tack the request id on to? I'm also wondering if there's something clever you can do with decorating a CompletionStage. I've always liked the idea of AspectJ, but I could never get past AOP being summarized by the `goto`-on-crack `return from`. – David Ehrmann Sep 25 '18 at 06:19
  • Hopefully this will all be in the past with [Project Loom](http://openjdk.java.net/projects/loom/) – David Ehrmann Sep 25 '18 at 06:22

0 Answers0