Usage of ContextPropagator in Java SDK

Hi there,

I’m trying to use ContextPropagator to pass the requestId and to be able to log the runId from all activities.
In the JavaDoc there is an example of how to implement and register an ContextPropagator, but I’m a bit lost on how to use there from inside the activities and/workflow code.

My goal is to be able to trace the requestId and runId on each log statement, having the requestId assigned on each signal/start

Any pointer any one can give?

Kind regards

1 Like

Hey I don’t know all that much about Java SDK so I’ll add @Vitaly. That being said, here is a test which uses ContextPropagator.

Hi Juan,

The idea of the ContextPropagator is that it’s called before and after your workflow client, workflow, and activity code is executed so that you can grab some contextual information and pass it along. The way that we use it is to grab some values from the org.slf4j.MDC in your workflow client thread and make sure that those values are populated in the MDC before your workflow code or activity code start.

This is a sample context propagator in the unit test: https://github.com/temporalio/sdk-java/blob/f0bbf84c496454d9909caefe6ca2784f76b8e592/temporal-sdk/src/test/java/io/temporal/internal/testing/WorkflowTestingTest.java#L878

The getCurrentContext() method is called before a workflow/child workflow/activity is started to grab the context from your code, then before your workflow/child workflow/activity starts, setCurrentContext() is called to set up the context in the child thread.

Does that help? You can define what “context” means, but those methods give you hooks to get/set it on your code’s threads.

3 Likes

Thanks so much. That gives me what I need to continue.