I have a Java Akka application and I want to set a separate MDC context for each message handling based on information inside the message, for example I have the following base interface for all messages:
public interface IdMessage {
String getId();
}
Also I have the following base actor for all actors:
public class BaseActor extends AbstractActor {
private final DiagnosticLoggingAdapter log = Logging.apply(this);
@Override
public void aroundReceive(PartialFunction<Object, BoxedUnit> receive, Object msg) {
if (msg instanceof IdMessage) {
final Map<String, Object> originalMDC = log.getMDC();
log.setMDC(ImmutableMap.of("id", ((IdMessage) msg).getId()));
try {
super.aroundReceive(receive, msg);
} finally {
if (originalMDC != null) {
log.setMDC(originalMDC);
} else {
log.clearMDC();
}
}
} else {
super.aroundReceive(receive, msg);
}
}
}
And the actual actor implementation:
public class SomeActor extends BaseActor {
SomeActor() {
receive(ReceiveBuilder
.match(SomeMessage.class, message -> {
...
}
}
}
I would like to make sure that all logs entries inside SomeActor#receive()
will have MDC context set in the BaseActor
. To make this work SomeActor#receice()
need to be executed in the same thread as BaseActor#aroundReceive()
method.
I didn't find any information about the behaviour of aroundReceive
- is that going to be always executed in the same thread as the actual receive
method? Based on my testing it's always executed in the same thread.