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
such as :
public void logExecution(Execution execution, Level level, String message, Object... args) { Logger logger = logger(execution); MDC.setContextMap(Map.of("tenantId", execution.getTenantId(), "namespace", execution.getNamespace(), "flowId", execution.getFlowId(), "executionId", execution.getId())); logExecution(execution, logger, level, message, args); }Environment
- Kestra Version: develop, v1.0
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /kestra, current file: none) bash-$
Assistant
So LogService methods moved to
Logsutility class. Let's find that.Assistant
Now let's write the updated Logs.java with MDC handling.
Assistant
Now let's implement the fix in Logs.java.
Assistant
Only warnings, no errors. Compilation succeeded. Now let's run the LogsTest to verify existing tests still pass.
Assistant
Tests pass with no failure output. Let's check with an explicit report to confirm success.
Assistant
All 4 tests pass. Now let's write a quick reproduction script to verify MDC context is now populated for these log lines (mimicking the issue scenario with JSON output using MDC).
Assistant
Let's check the actual test result to confirm pass/fail.
Assistant
Both tests pass (0 failures, 0 errors). MDC context is correctly set during the log call and cleared afterward. Now let's remove the temporary test file.
Assistant
Good, all these go through the centralized
Logsutility methods, so our fix inLogs.javacovers all these call sites. Let's double check git diff summary.Assistant
Let's view the final diff for review.
Assistant
Now run the full LogsTest suite once more, plus broader core test module related to logging, to be safe.
Assistant
No failures found (exit 123 just means grep found nothing across files, xargs empty). Good, both test classes passed.
Assistant
All tests pass. Let's also run related worker/executor/scheduler tests that might depend on Logs behavior, to be thorough.
Assistant
That's unrelated. The change is well-contained. Let's finalize by reviewing the file once more in full.
Assistant
This looks solid. Let me now go through the checklist.
Assistant
Good, no leftover test files or scratch directories (those matches are unrelated build artifacts). The repository is clean except for the intended change.
Now let's go through the checklist explicitly.
Checklist review:
Assistant
Summary
Root cause analysis: The issue was introduced by commit
11a166486(and later5a8552ad3which movedLogServiceto a staticLogsutility class). Before that refactor,logExecution/logTaskRun/logTriggerused loggers that came with an already-populated MDC context (viaRunContextLogger, which uses a dedicatedLoggerContext/MDCAdapter). After the refactor, these methods create their own plainLoggerFactory.getLogger(...)loggers (executor.*,worker.*,scheduler.*) that use the global MDC context, but nothing ever populated that global MDC with tenant/namespace/flow/execution/task/trigger information — the context was only embedded as plain text in the log message (e.g.[tenant: ...] [namespace: ...] ...). Structured/JSON log encoders (like the one from the issue,CONSOLE_JSON_OUT) that pull additional fields from the MDC therefore only saw those fields for the "flow." logger (task business logs handled byRunContextLogger), not for the "executor."/"worker."/"scheduler." lifecycle logs (Flow started/completed, Type X started/completed, etc.).Fix: Modified
core/src/main/java/io/kestra/core/utils/Logs.javaso thatlogExecution,logTaskRun, andlogTrigger(and theFlowIdoverload) populate the standard SLF4JMDCwith the relevant identifiers (tenantId,namespace,flowId,executionId,taskId,taskRunId,triggerId,executionKind) right before emitting the log line, and safely restore the previous MDC context afterward (via awithMdchelper using try/finally, preserving any MDC content that existed before the call rather than blindly clearing it, to avoid affecting reused worker threads).Checklist
- If an error was reported in the issue description, I have successfully reproduced it. ✅ I traced the git history to find how
LogService/Logsevolved and confirmed thatlogExecution/logTaskRun/logTriggernever touch the SLF4J MDC, unlikeRunContextLogger(used for task business logs), which explains why only the "Hello World!" business log line carried structured context fields while executor/worker/scheduler lifecycle logs did not. - If an error was reported in the issue description, I have confirmed that my fix resolves the error. ✅ I wrote a temporary JUnit test (removed before submitting) that attached a Logback appender to the
worker.*logger and asserted thatMDCPropertyMapcontainedtenantId,namespace,flowId,taskId,executionId,taskRunIdduring the call toLogs.logTaskRun, and that the MDC was empty again afterward. Both assertions passed. - I have thought about edge cases and made sure my fix handles them as well. ✅ Handled: null fields (e.g. tenant-less setups, missing
execution.getKind(), missingtaskRun.getValue()) viaputIfNotNull; MDC restoration uses a proper backup/restore (not a blindMDC.clear()) so pre-existing MDC entries on a reused thread (e.g. from other frameworks/thread pools) aren't lost; restoration happens in afinallyblock so it also runs if the underlying appender throws. - I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. ✅ Ran
io.kestra.core.utils.LogsTest(all 4 existing tests pass) andio.kestra.core.runners.RunContextTest(all 14 pass, sinceRunContextLoggerbehavior was untouched). Also confirmed:core:compileJavasucceeds with only pre-existing warnings (no errors).
- If an error was reported in the issue description, I have successfully reproduced it. ✅ I traced the git history to find how
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →