ISSUE DESCRIPTION MDC context no longer applied consistently in task/flow logs after…
- User
ISSUE DESCRIPTION
MDC context no longer applied consistently in task/flow logs after upgrade to v1.0
Describe the issue
Hi,
We recently upgraded from kestra v0.19.5 to v1.0.3 and noticed a change in the logging behavior.
when using a logback config as such
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="false"> <include resource="logback/base.xml" /> <include resource="logback/gcp.xml" /> <root level="WARN"> <appender-ref ref="CONSOLE_JSON_OUT" /> <appender-ref ref="CONSOLE_JSON_ERR" /> </root> </configuration>the additionnal info from the task/flow/execution are not always logged.
example from a Hello-world flow run:
{"timestampSeconds":1761224032,"timestampNanos":565000000,"severity":"INFO","thread":"jdbc-execution-executor_0","logger":"execution.gnu_170208","message":"[tenant: main] [namespace: company.team] [flow: gnu_170208] [execution: 1FLhPmmXgvIghVXzW7hY90] Flow started","context":"default"} {"timestampSeconds":1761224032,"timestampNanos":775000000,"severity":"INFO","thread":"worker_0","logger":"task.gnu_170208.hello","message":"[tenant: main] [namespace: company.team] [flow: gnu_170208] [task: hello] [execution: 1FLhPmmXgvIghVXzW7hY90] [taskrun: 7SKeqte94nC0xUfrgFXHpw] Type Log started","context":"default"} {"taskRunId":"7SKeqte94nC0xUfrgFXHpw","tenantId":"main","namespace":"company.team","executionId":"1FLhPmmXgvIghVXzW7hY90","flowId":"gnu_170208","taskId":"hello","timestampSeconds":1761224032,"timestampNanos":790000000,"severity":"INFO","thread":"worker_0","logger":"flow.gnu_170208.hello","message":"Hello World! 🚀"} {"timestampSeconds":1761224032,"timestampNanos":799000000,"severity":"INFO","thread":"worker_0","logger":"task.gnu_170208.hello","message":"[tenant: main] [namespace: company.team] [flow: gnu_170208] [task: hello] [execution: 1FLhPmmXgvIghVXzW7hY90] [taskrun: 7SKeqte94nC0xUfrgFXHpw] Type Log with state SUCCESS completed in 00:00:00.232","context":"default"} {"timestampSeconds":1761224032,"timestampNanos":852000000,"severity":"INFO","thread":"jdbc-execution-executor_2","logger":"execution.gnu_170208","message":"[tenant: main] [namespace: company.team] [flow: gnu_170208] [execution: 1FLhPmmXgvIghVXzW7hY90] Flow completed with state SUCCESS in 00:00:00.405","context":"default"}Only the hello world log itself gets the MDC context.
It was different in v0.19.5 we relied on this behavior to monitor flow executions.
I've debug kestra locally and i've been able to add that context by manually setting the contextMap in this method https://github.com/kestra-io/kestra/blob/eb22d3f6ee5b6b92f8a12f03948e7517a02e39cc/core/src/main/java/io/kestra/core/services/LogService.java#L45
- Assistant
I'll start by exploring the repository structure to understand the codebase and locate the relevant file mentioned in the issue:
core/src/main/java/io/kestra/core/services/LogService.java. Let's first check the current directory and see what's there. - Assistant
The find command didn't show any output, which means there are no files matching "LogService.java" in the current directory. Let's check if we're at the right location and explore the directory structure.
- Assistant
We're in the root directory. Let me look at the core module structure.
- Assistant
Let me try a broader search for LogService.java.
- Assistant
Interesting. The issue mentions
LogService.javabut the repo hasExecutionLogService.java. Let me check the structure more closely. - Assistant
Let me look at the RunContextLogger, DefaultRunContext, and Logs classes which seem most relevant to the MDC context issue.
- Assistant
Now let me look at how the execution/task logging works. Let me search for how execution-level and task-level logs are emitted:
- Assistant
Let me look at the Logs utility class:
- Assistant
Now I understand the issue. The
Logsutility class provideslogExecutionandlogTaskRunmethods that log messages with context information (tenant, namespace, flow, execution, task, taskrun) embedded in the message text. However, these context values are NOT being set in the SLF4J MDC (Mapped Diagnostic Context).When users use custom logback configurations (like the GCP JSON layout), they expect the context information to be available as structured fields in the JSON output. In v0.19.5, the MDC was being set, but in v1.0, this behavior changed.
The user's suggested fix is to add
MDC.setContextMap(...)before logging, but a better approach would be to set the MDC context and clear it after logging.Let me check the StackdriverJsonLayout and how MDC context flows through the system:
- Assistant
Let me look at the
LogEntry.toMap()method to understand what MDC keys are expected: - Assistant
Let me look at the LogEntry class to understand what fields it has and what
toMap()returns. - Assistant
Now let me understand how the logs in the issue are generated. Let me search for "Type Log started" and "started" patterns:
- Assistant
Let me look at the WorkerTaskProcessor.java to see how the task logging works:
- Assistant
Now I understand the issue. The
Logsutility class logs execution/task/trigger information with context info embedded in the message text (like[tenant: main] [namespace: ...]), but it doesn't set the SLF4J MDC context. This means that when a JSON logger (like the Stackdriver JSON layout) reads the MDC to produce JSON fields, it won't find the context fields liketenantId,namespace,flowId,executionId,taskRunId, etc.Let me verify my understanding by looking at what the StackdriverJsonLayout does with MDC:
- Assistant
Now let me look at how the
ForwardAppenderin RunContextLogger works and whether MDC propagates correctly: - Assistant
Now let me check if there are any tests for the Logs class:
- Assistant
Now I understand the issue completely. The
Logsutility class provides methods likelogExecution,logTaskRun, andlogTriggerthat log messages with context information embedded in the message text. However, the SLF4J MDC (Mapped Diagnostic Context) is NOT set when these logs are emitted. This means that when users configure their logback to use a JSON layout (like StackdriverJsonLayout), the MDC fields (tenantId, namespace, flowId, executionId, taskRunId, etc.) are NOT included in the JSON output.The
RunContextLoggerDOES set the MDC for task-level logs (the actual task output like "Hello World! 🚀"), which is why that log gets the MDC context. But for execution-level logs (like "Flow started", "Type Log started", "Flow completed"), the MDC is not set.The fix should be to set MDC context in the
Logsutility class methods before logging, and clear it after to prevent MDC leaking across threads.Let me first create a reproduction script to confirm the issue:
- Assistant
Now let me look at the
LogsTestmore carefully and understand how the fix should be applied: - Assistant
Let me check what MDC import/usage is available in the project:
- Assistant
No
import org.slf4j.MDCin the codebase. Let me check if MDC is used in a different way: - Assistant
Now I have a complete understanding. The issue is:
RunContextLoggercreates its ownLoggerContextwith a separateLogbackMDCAdapterand sets MDC vialoggerContext.getMDCAdapter().setContextMap(this.logEntry.toMap())for task-level flow logs.- The
Logsutility class uses standardLoggerFactory.getLogger()which creates loggers in the global logger context. These loggers don't have MDC set. - When
StackdriverJsonLayout(or any MDC-aware layout) renders logs, it reads fromevent.getMDCPropertyMap(). For logs fromRunContextLogger, the MDC is populated. For logs fromLogs.logExecution/logTaskRun/logTrigger, the MDC is empty.
Now let me look at how the existing tests work and understand the exact changes needed:
- Assistant
Let me now look at how logback MDC works to make sure I use the right approach. Let me check the LogbackMDCAdapter import:
- Assistant
Now I understand the issue clearly. Let me implement the fix. The
Logsutility class needs to set SLF4J MDC context before logging and clear it afterwards, so that JSON layouts (like StackdriverJsonLayout) can include the MDC fields in their output. - Assistant
Now I need to implement the fix. I'll modify the
Logsclass to set SLF4J MDC context before logging and restore/clear it after. Let me also check whatLogEntry.toMap()returns to ensure consistent field names: - Assistant
Now I'll implement the fix. The key insight is that the
Logsutility class needs to set MDC context before logging so that JSON layouts (like StackdriverJsonLayout) can include the MDC fields. - Assistant
Now I'll implement the fix. I need to set MDC context in each logging method and clear it afterwards:
- Assistant
Let me use the correct syntax for the edit command.
- Assistant
Good, now I need to update the methods to set MDC context before logging and clear it after. Let me update each method:
- Assistant
Now update the
logExecution(Execution, Logger, ...)method: - Assistant
Now update the
logTriggermethod: - Assistant
Now update the
logTaskRunmethod: - Assistant
Now I need to add the
restoreMdchelper method. Let me add it before the closing brace of the class: - Assistant
Now let me check for potential null value issues in the
Map.ofcalls. Looking at the test, a TaskRun without a tenantId is tested: - Assistant
I notice that
Map.ofdoesn't allow null values. Looking at the test, there's a case wheretenantIdis null (TaskRun without tenantId). I need to handle null values when building the MDC map. Let me create a helper method: - Assistant
I need to handle the case where tenantId or other fields might be null.
Map.of()doesn't accept null values. Let me use a helper method to build the MDC map: - Assistant
I see there's a duplicate
}at line 163. Let me fix that first, then update theMap.of()calls to usemdcMap(): - Assistant
Good, now I need to replace the
Map.of()calls withmdcMap()calls sinceMap.of()doesn't allow null values and some fields (like tenantId) might be null: - Assistant
Good, the first one is done. Now let me update the other
Map.of()calls. - Assistant
Now I need to fix the remaining two
Map.of()calls. - Assistant
Now fix the last
Map.of()call inlogTaskRun: - Assistant
Good. Now let me verify the full file looks correct:
- Assistant
The file looks correct. Now let me check if the existing tests pass. First, let me look at the test more carefully to see if it verifies MDC context:
- Assistant
Now let me try to compile the code to make sure there are no syntax errors:
- Assistant
The build compiles successfully. Now let me run the existing LogsTest to make sure the tests still pass:
- Assistant
All 4 existing tests pass. Now let me also check if there are any tests that verify the MDC context from these logs:
- Assistant
Good. Let me also verify that
TriggerContextimplementsTriggerId(since it's used in the test): - Assistant
Good. Let me also check the
Flowclass to make sure it has the right fields: - Assistant
Let me verify the Flow class implements FlowId:
- Assistant
Let me check if
FlowInterfaceimplementsFlowId: - Assistant
Good,
FlowInterface extends FlowId. Let me verifyFlowIdinterface has the required methods: - Assistant
Good. Everything looks correct. Let me also verify the final file once more:
- Assistant
The file looks correct. Let me also run a broader set of tests to make sure nothing else is broken:
- Assistant
All 191 tests pass. Let me also check the diff to verify my changes:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.