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<?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:
json{"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"} Assistant
I'll start by exploring the repository structure and finding the relevant files mentioned in the issue.
Assistant
The command didn't find LogService.java. Let me try a broader search.
Assistant
The
findcommand returned no output (just the prompt), which is unusual. Let me check what's in the current directory first.Assistant
Let me explore the core directory to find the LogService.java file.
Assistant
I don't see a
LogService.javafile in the services directory. Let me search for it more broadly.Assistant
Let me search for the log-related methods mentioned in the issue:
Assistant
Let me look at the Logs.java file which seems to be the logging utility:
Assistant
I need to use the open command without the leading slash.
Assistant
Let me try using cat to view the file:
Assistant
Now I can see the issue. The
Logs.javaclass logs messages using string formatting (the prefix with{}) rather than setting MDC context. This is why the MDC context is not being applied consistently. Let me also check if there's an MDC utility or how it's used elsewhere:Assistant
Let me examine these files to understand how MDC is currently being used:
Assistant
Now let me check the DefaultRunContext to understand the MDC usage better:
Assistant
Let me understand the issue better. Looking at the code:
- The
Logs.javaclass is used to log execution/trigger/taskrun messages but it uses string formatting (via{}placeholders) instead of MDC. - The issue mentions that MDC context is not being applied consistently.
- In
RunContextLogger.java, we can see that MDC context is properly set for task logs (line ~177:loggerContext.getMDCAdapter().setContextMap(this.logEntry.toMap());).
The issue is that
Logs.javadoesn't set MDC context. The user suggests adding MDC context in methods likelogExecution. Let me check how the log messages flow through the system:- The
Assistant
Now let me look at where
Logs.javais called from to understand the execution flow:Assistant
Let me also look at the test file to understand the expected behavior:
Assistant
Now let me check the issue more closely. The issue is that when using custom logback configurations, the MDC context (tenantId, namespace, executionId, flowId, etc.) is not available in the log events. Let me check how the logback adapter sets MDC context in the
Logs.javamethods:Assistant
So
org.slf4j.MDCis not used anywhere in the codebase currently. The issue is that whenLogs.javamethods are called, they don't set MDC context, which means that external logback appenders (like the JSON ones in the issue) don't get the context information.Let me check what
LogEntry.toMap()returns to understand what fields should be in MDC:Assistant
Now I understand the issue. The
toMap()method returns a map with keys liketenantId,namespace,flowId,taskId,executionId,taskRunId, etc. WhenRunContextLoggeris initialized, it sets this map as the MDC context (line ~177 in RunContextLogger.java), so task logs get the MDC context.However, the
Logs.javaclass doesn't set MDC context before logging. It only uses string formatting with placeholders. This means that when logs are written usingLogs.logExecution(),Logs.logTaskRun(), orLogs.logTrigger(), the MDC context is empty, so external logback appenders can't access these fields.The fix is to set the MDC context before logging and clear it after in the
Logs.javaclass. Let me create the fix:Assistant
Now I need to modify the
Logs.javaclass to set MDC context before logging and clear it afterward. I'll add the MDC import and modify each logging method:Assistant
Now let me verify the file was written correctly:
Assistant
Good. Now let me run the existing tests to make sure my changes don't break anything:
Assistant
The test is failing because
Map.of()doesn't allow null values, and some fields liketenantIdcan be null. I need to handle null values properly. Let me fix this:Assistant
Now let me run the tests again:
Assistant
There are compilation errors. Let me check what the issue is:
Assistant
I see the issue. The
Supplier<Void>expects a return value. I should useRunnableinstead:Assistant
All 4 tests pass now. Let me also verify that the MDC context is actually being set by looking at the test more closely and adding a quick test to verify MDC is populated:
Assistant
Let me now run a broader test to make sure I haven't broken anything else:
Assistant
Let me run a quicker test focusing on related tests:
Assistant
All 37 log-related tests passed. Now let me verify the changes I made and check if there are any edge cases I need to consider:
Assistant
Now let me verify the diff to see exactly what changes were made:
Assistant
Let me also run some tests in the executor and worker modules to make sure the change doesn't break anything there since those modules use the
Logsclass:Assistant
There's one failing test. Let me check what failed:
Assistant
command
Assistant
Let me run the worker tests again with more output to see which test failed:
Assistant
command
Assistant
The worker tests pass now. The previous failure might have been a flaky test. Let me also run the executor tests:
Assistant
Now let me write a simple test script to verify that the MDC context is properly set and cleaned up:
Assistant
Now let me also check the scheduler tests since they also use the Logs class:
Assistant
All scheduler tests pass. Now let me verify my solution handles edge cases properly:
-
Null values in context: The
newContextMapmethod filters out null values, which is important becausetenantIdcan be null for flows without tenants. -
MDC cleanup: The
logWithMDCmethod properly saves the previous MDC context and restores it in afinallyblock, ensuring MDC is cleaned up even if an exception occurs. -
Thread safety: MDC uses ThreadLocal internally, so each thread has its own MDC context. Our implementation saves and restores the context properly.
Let me also check if there are any other places where MDC might need to be set (e.g., for value field in TaskRun):
-
Assistant
Let me check what fields
toMap()includes to make sure I'm setting all the same fields:Assistant
I see that
toMap()also includesexecutionKind. Let me check if theLogsmethods should also include this field. Looking at the execution objects, they might haveexecutionKind:Assistant
command
Assistant
So
Executionhas akindfield. However, looking at the original issue description, the user's fix example only includestenantId,namespace,flowId, andexecutionIdfor the Execution logging. TheexecutionKindfield is typically only relevant for task runs.Let me look at the original
LogEntry.toMap()to see what fields are actually used in practice:Assistant
Looking at the issue description, the user's workaround only includes
tenantId,namespace,flowId, andexecutionIdfor execution logging. My implementation is consistent with this. TheexecutionKindfield is mainly used in task-level logging throughRunContextLogger, not in the system logging done byLogs.java.Let me verify my changes are correct and complete:
Assistant
I need to continue with my verification and testing. Let me run the LogsTest again to confirm everything is working.
Assistant
All tests are passing. Let me now verify the final state of my changes and submit.
Assistant
I need to use the bash_terminal function to run a command.
Assistant
I have successfully implemented the fix for the MDC context issue. Here's my summary:
Summary of Changes
I modified
core/src/main/java/io/kestra/core/utils/Logs.javato set MDC (Mapped Diagnostic Context) before logging, which allows logback appenders to access context information liketenantId,namespace,flowId,executionId, etc.Key Changes:
- Added imports for
java.util.HashMap,java.util.Map, andorg.slf4j.MDC - Created helper method that builds a context map from key-value pairs, filtering out null values
- Added imports for
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.