Custom key-value in MDC per Process Instance

Hello,

I have a spring-boot app that uses camunda-bpm-spring-boot-starter to run process instances in an embedded camunda BPM engine.

The app implements REST APIs - when invoked, the API will start a process instance as below.

@PostMapping("/start")
public void start() {
    Map<String, Object> processVariables = new HashMap<>();
    processVariables.put(VAR_001, someValue);
    processVariables.put(VAR_002, someValue);
    ProcessInstance processInstance = runtimeService
        .startProcessInstanceByKey(PROCESS_DEF_KEY, businessKey, processVariables);
}

I want to set a specific custom tracing ID field (which is essentially a UUID string value with a custom prefix) into the Mapped Diagnostic Context (MDC) when I start each process instance such that this will remain in the MDC and can be used throughout the life of each process instance. Each log written within any task in the process instance must therefore have this tracing ID field from the MDC.

How can I achieve this?

I looked into https://docs.camunda.org/manual/latest/user-guide/logging/#process-data-context and how I can possibly use ProcessDataLoggingContext to set my own key-value into the MDC for a process instance, but it appears like I can only set values for one of the pre-defined properties (propertyActivityId, propertyApplicationName etc.) in this class.

Appreciate any help in this regard.
Thanks!

I think that perhaps you could use the business key concept to pass an Id that will exist as long as the process and sub processes do.

You can read more about how to use business keys in this blog post.

Thanks @Niall, but I already have a valid business key that I am using for each process instance.
Thinking along these lines, I can as well keep the tracing ID as a process variable.

Instead, what I actually want is to be able to set a key-value pair specifically in the MDC for the entire process instance.

Just wondering if there is a way to do that.

Is there a reason you don’t want to use process variables for this?
Process variables are just key value pairs at their core.

@Niall

My ultimate goal is to be able to keep this key-value pair in MDC and provide it to my logging appender so that it can log this, and use this tracing ID value for filtering / tracing all logs which are part of the same process instance flow (including any external API invocations etc. done by the process instance).

As you suggested, if I keep this in a process variable, I would be required to explicitly set this in the MDC context at the beginning of each task. Is that correct?

If this is the only possible way, then we have no choice.
I am just wondering if there is a less tedious and cleaner way to do this.

I can’t speak to “the MDC context” but if you set a process variables at the beginning of the process in the global scope it will be available to all tasks that need it throughout the lifecycle of the process instance.