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
The issue is about MDC (Mapped Diagnostic Context) context not being applied consistently in task/flow logs after upgrading to v1.0.
Let me first explore the repository structure to understand the codebase and then find the relevant files to fix this issue.
The issue description mentions:
- The problem is with MDC context not being applied consistently
- The user suggests setting MDC context in the
LogService.javafile - The suggested fix is to manually set the contextMap using
MDC.setContextMap()
Let me start by exploring the repository structure and then look at the LogService.java file mentioned.
Assistant
Now let me find the LogService.java file in the core directory:
<tool_call> <function=bash_terminal> <parameter=command> find /kestra/core -type f -name "LogService.java" 2>/dev/null </tool_call>
Assistant
The previous command didn't get a response. Let me try again with the find command.
Assistant
The command completed without output. Let me check the core directory structure to find Java files.
<tool_call> <function=bash_terminal> <parameter=command> ls -la /kestra/core </tool_call>
Assistant
The find command returned with exit code 0 but no output. Let me check the core directory structure directly.
Assistant
The core directory contains source code. Let me look for the LogService.java file in the src directory.
<tool_call> <function=bash_terminal> <parameter=command> find /kestra/core/src -name "*.java" | head -50 </tool_call>
Assistant
The command executed but no output was shown. Let me try again with the find command to list Java files.
Assistant
Good, I can see there are Java files. Let me search for LogService.java specifically.
<tool_call> <function=bash_terminal> <parameter=command> find /kestra -name "LogService.java" 2>/dev/null </tool_call>
Assistant
The command executed without errors but no output. Let me try again with grep to find the file.
Assistant
The find command returns exit code 0 but no output. This means either the file doesn't exist or there's an issue. Let me try using grep to search for "class LogService" in Java files.
Assistant
The grep returned exit code 1, meaning no matches found. Let me search for files that might be related to logging, MDC context, or execution logging.
Assistant
Good, I found references to MDC in the codebase. Let me look at the RunContextLogger.java file to understand how MDC is being used, and then find where logging for execution and tasks happens.
<tool_call> <function=bash_terminal> <parameter=command> cat /kestra/core/src/main/java/io/kestra/core/runners/RunContextLogger.java </tool_call>
Assistant
The command executed but I didn't provide it correctly. Let me try again with the cat command to view the RunContextLogger.java file.
Assistant
Now I understand the structure. The RunContextLogger is responsible for logging and it uses LogbackMDCAdapter to set the MDC context. Let me look at where the logging is initiated for executions and tasks. The issue is that the MDC context is set when the logger is initialized, but it seems like the MDC context isn't being propagated to certain logging calls.
Let me search for how execution and task logs are logged - looking for code that logs execution and task information.
<tool_call> <function=bash_terminal> <parameter=command> grep -r "logExecution|logger(execution)" /kestra/core/src --include="*.java" 2>/dev/null | head -30 </tool_call>
Assistant
Let me try the grep command again to search for log execution related code.
Assistant
Now I found the relevant file -
Logs.javain the utils directory. Let me examine this file to see the current implementation and understand how to fix the MDC context issue.Assistant
Now I understand the issue. The
Logs.javautility class is logging execution, trigger, and task run information directly usingLoggerFactory.getLogger()and logging with the information prefixed to the message. However, this is being done outside of theRunContextLoggermechanism that uses MDC.The issue is that when using logback's JSON appenders, the MDC context is not being propagated because:
- The
Logs.logExecution()andLogs.logTaskRun()methods useLoggerFactory.getLogger()to get a logger - These loggers don't have the MDC context set (unlike
RunContextLoggerwhich sets it vialoggerContext.getMDCAdapter().setContextMap(this.logEntry.toMap()))
Looking at the issue description, the user suggests adding
MDC.setContextMap()to set the context manually. Let me also check what theLogEntry.toMap()method returns to understand what context is being set.<tool_call> <function=bash_terminal> <parameter=command> find /kestra -name "LogEntry.java" 2>/dev/null </tool_call>
- The
Assistant
The command is being executed but not returning output. Let me try again with the find command to locate LogEntry.java.
Assistant
Now let me examine the LogEntry.java file to see what the toMap() method returns:
Assistant
Now I understand the issue better. The
toMap()method returns a map with tenantId, namespace, flowId, taskId, executionId, taskRunId, triggerId, and executionKind.The problem is that when
Logs.javalogs execution and task run information, it's not using the MDC context mechanism thatRunContextLoggeruses. TheLogs.logExecution()andLogs.logTaskRun()methods are callingLoggerFactory.getLogger()to get a logger and then logging directly, which doesn't benefit from the MDC context that would be set byRunContextLogger.The fix suggested by the user is to use
MDC.setContextMap()to set the MDC context before logging. However, since we're working with slf4j, we should useorg.slf4j.MDCto set the context.Let me check how MDC is imported and used in the codebase:
<tool_call> <function=bash_terminal> <parameter=command> grep -r "import.MDC" /kestra/core/src --include=".java" 2>/dev/null | head -10 </tool_call>
Assistant
Let me try the grep command again to search for MDC imports.
Assistant
The only MDC-related import is for
LogbackMDCAdapter. Let me check iforg.slf4j.MDCis being used anywhere:<tool_call> <function=bash_terminal> <parameter=command> grep -r "org.slf4j.MDC|import slf4j.MDC" /kestra/core/src --include=".java" 2>/dev/null | head -10 </tool_call>
Assistant
Let me try the command again to search for MDC usage in the codebase.
Assistant
The grep command returned exit code 0, meaning the search succeeded but found no results. Let me search for MDC in a different way - looking for usages without the full package path.
Assistant
The grep command returned exit code 0, meaning no MDC usage was found with the dot notation. This confirms that MDC is not being used in the codebase outside of RunContextLogger.
Now I understand the issue. The
Logs.javaclass needs to be modified to set the MDC context before logging, and then clear it afterwards. This will ensure that the MDC context is propagated to the logback appenders.Let me fix the Logs.java file to set the MDC context properly. The fix should:
- Set the MDC context using
MDC.setContextMap()before logging - Clear the MDC context after logging (using a finally block)
Let me first check if there are any existing tests for Logs.java:
<tool_call> <function=bash_terminal> <parameter=command> cat /kestra/core/src/test/java/io/kestra/core/utils/LogsTest.java </tool_call>
- Set the MDC context using
Assistant
The command executed but I need to provide it correctly. Let me try the cat command to view the LogsTest.java file.
Assistant
Now I have a complete understanding of the issue. The problem is that the
Logs.javautility class is logging execution, trigger, and task run information usingLoggerFactory.getLogger()directly, which doesn't benefit from the MDC context mechanism thatRunContextLoggeruses.Looking at the issue description, only the "Hello World" log (which comes from the task execution within
RunContextLogger) gets the MDC context, while the wrapper logs fromLogs.logExecution()andLogs.logTaskRun()don't include the MDC context in the output (notice the"context":"default"in the logs that don't have MDC).The fix should:
- Set the MDC context using
MDC.setContextMap()before logging inLogs.java - Clear the MDC context after logging (using a finally block)
Let me now modify the Logs.java file:
- Set the MDC context using
Assistant
Assistant
The command was executed but I didn't provide the tool call properly. Let me try again with the proper tool call syntax to create and view the fixed Logs.java file.
Assistant
The command exited successfully. Now let me view the file to verify it was created correctly, then copy it to the actual location.
<tool_call> <function=bash_terminal> <parameter=command> cat /tmp/logs_fix.java </tool_call>
Assistant
Let me try the cat command to view the file.
Assistant
Assistant
The command executed but I need to check the output. Let me verify the file was created correctly.
Assistant
The command completed successfully. Now let me verify the file was copied correctly by viewing it.
Assistant
I notice the file still has the unused imports
java.util.Optionalandio.kestra.core.models.executions.ExecutionKind. Let me fix this by removing those unused imports. I should also verify if the fix is correct by running the existing tests.First, let me remove the unused imports from the file.
<tool_call> <function=bash_terminal> <parameter=command> sed -i '/import java.util.Optional;/d; /import io.kestra.core.models.executions.ExecutionKind;/d' /kestra/core/src/main/java/io/kestra/core/utils/Logs.java </tool_call>
Assistant
Let me check if the file was updated correctly by viewing it:
Assistant
The file still has the unused imports
java.util.Optionalandio.kestra.core.models.executions.ExecutionKind. Let me remove those using sed:<tool_call> <function=bash_terminal> <parameter=command> sed -i '/import java.util.Optional;/d' /kestra/core/src/main/java/io/kestra/core/utils/Logs.java </tool_call>
Assistant
The sed command executed. Let me verify the changes and then also remove the ExecutionKind import.
Assistant
Now let me verify the file is correct by viewing it:
Assistant
I notice that
java.util.Optionalis still present as an import but is not being used. Let me remove it and verify the file is clean.Actually, I also need to think about edge cases. Looking at the current implementation:
- When we call
MDC.putAll(mdcContext), we're adding new context variables to the existing MDC context. This is good because we preserve any existing context. - When we call
mdcContext.forEach(MDC::remove), we're removing only the keys we added, which should restore the original MDC context (if it had the same keys before, they will be restored to their previous values).
Wait, this isn't quite correct. If the MDC already had some of these keys, removing them will not restore the previous values. Let me fix this by saving and restoring the full context.
Actually, looking at how MDC works in slf4j, when you use
MDC.putAll(), it adds/overwrites entries. When you useMDC.remove(), it removes the entry. This means if we want to restore the original state, we need to save the full context before and restore it after.Let me revise the approach to properly save and restore the MDC context:
- When we call
Assistant
Let me verify the current state of the file first and then rewrite it with the proper MDC context handling.
Assistant
I see the file still has the unused
import java.util.Optional;. Let me fix this and also update the MDC context handling to properly save and restore the original context. I'll rewrite the file with the correct implementation.Assistant
Let me verify the file was created correctly:
Assistant
The file looks good now. Now I need to run the existing tests to make sure the changes work correctly. Let me run the LogsTest to verify:
<tool_call> <function=bash_terminal> <parameter=command> cd /kestra && ./gradlew :core:test --tests "io.kestra.core.utils.LogsTest" 2>&1 | tail -50 </tool_call>
Assistant
Let me try the gradle command again properly.
Assistant
The tests passed. Now let me also run the complete test suite to make sure I didn't break anything else. But first, let me verify the changes with the git diff:
<tool_call> <function=bash_terminal> <parameter=command> cd /kestra && git diff </tool_call>
Assistant
Let me check the git diff to see the changes made:
Assistant
The git diff shows the changes I made. The changes look correct. Now let me verify that the fix is complete by checking if there are any other places where logging might be happening that needs MDC context. Let me also run some more tests to ensure the fix works correctly in various scenarios.
Let me first check if there are any other places that use logging utilities:
<tool_call> <function=bash_terminal> <parameter=command> cd /kestra && git diff --stat </tool_call>
Assistant
Let me check the git diff stat to see the changes summary.
Assistant
The fix looks good. The changes are:
- Added MDC context handling to
logExecution,logTrigger, andlogTaskRunmethods - Added helper methods
buildMdcContextfor each entity type
Now let me verify the fix handles edge cases properly. One thing I notice is that I need to handle the case where the
previousContextcould be null. Let me check ifMDC.getCopyOfContextMap()returns null when there's no context and ifMDC.setContextMap(null)is valid.Actually, looking at slf4j documentation,
MDC.getCopyOfContextMap()returns null if there's no context, andMDC.setContextMap(null)clears all context. So the fix should handle this correctly.Let me run a broader set of tests to ensure the fix doesn't break anything:
<tool_call> <function=bash_terminal> <parameter=command> cd /kestra && ./gradlew :core:test --tests "io.kestra.core.utils.*" 2>&1 | tail -30 </tool_call>
- Added MDC context handling to
Assistant
The command executed but I need to check if it's running properly. Let me wait for the output or check the status.
Assistant
All 191 tests in the
io.kestra.core.utilspackage passed! This confirms that the fix doesn't break any existing functionality.Now let me also check if there are any other places that might need MDC context updates. Looking at the issue description, the user mentions that the logs from task/flow/execution are not always logged with the MDC context. The fix I made should address this by setting the MDC context before logging.
Let me also check if there are any other logging utilities or methods that might need the same treatment. Let me search for other places that use LoggerFactory:
<tool_call> <function=bash_terminal> <parameter=command> grep -r "LoggerFactory.getLogger" /kestra/core/src/main/java --include="*.java" 2>/dev/null | head -20 </tool_call>
Assistant
Let me check the command output to see where LoggerFactory.getLogger is used.
Assistant
The grep output shows that
LoggerFactory.getLoggeris used in many places. TheLogs.javafile is the only utility class that logs execution, trigger, and task run information. Other places use logger instances that are part of theRunContextLoggermechanism, which already handles MDC context.The fix I made to
Logs.javashould be sufficient to address the issue described in the problem. Let me now run a broader set of tests to ensure the fix doesn't break anything else in the codebase:<tool_call> <function=bash_terminal> <parameter=command> cd /kestra && ./gradlew :core:test --tests "io.kestra.core.runners.*Test" 2>&1 | tail -50 </tool_call>
Assistant
Let me wait for the test output to complete:
Assistant
There is a failing test. Let me check which test failed and why. Let me look at the test report or find out which test failed:
<tool_call> <function=bash_terminal> <parameter=command> cd /kestra && cat /kestra/core/build/reports/tests/test/index.html 2>/dev/null | grep -i "failed" | head -10 </tool_call>
Assistant
Let me check which test failed by looking at the test output more carefully:
Assistant
The output doesn't show which specific test failed. Let me check the test report file or re-run the tests with more verbose output to see which test failed:
<tool_call> <function=bash_terminal> <parameter=command> cd /kestra && ./gradlew :core:test --tests "io.kestra.core.runners.*Test" --info 2>&1 | grep -A 5 "FAILED|failed" | head -30 </tool_call>
Assistant
Let me check the test report XML file to find the failing test:
Assistant
Let me search for the failing test result XML file:
<tool_call> <function=bash_terminal> <parameter=command> grep -l "failures="1"" /kestra/core/build/test-results/test/*.xml 2>/dev/null | head -5 </tool_call>
Assistant
The command is executing but I need to see the output. Let me try a different approach to find the failing test.
Assistant
The failing test is
io.kestra.core.runners.FilesServiceTest. Let me check what the failure is about:Assistant
The failing test is
testOutputFilesWithSpecialCharacters(Path)inFilesServiceTest. The failure is:java.nio.file.InvalidPathException: Malformed input or input contains unmappable characters: สวัสดี&.txtThis is a test failure related to handling special characters (Thai script) in file names, not related to my MDC changes. The error is in the test itself, trying to use a file with Thai characters in the name. This is an environment issue (the test environment doesn't support the Thai character encoding properly) and is not related to my fix.
Let me verify that the LogsTest passes, which is the specific test for the logging functionality I modified:
<tool_call> <function=bash_terminal> <parameter=command> cd /kestra && ./gradlew :core:test --tests "io.kestra.core.utils.LogsTest" 2>&1 | tail -20 </tool_call>
Assistant
The command is executing but I need to wait for the output. Let me wait for the test output to complete.
Assistant
The LogsTest passed! The test that failed (
testOutputFilesWithSpecialCharacters) is unrelated to my fix - it's a pre-existing issue with handling special characters in file names in the test environment.Now let me verify the fix is correct by summarizing what was done:
-
: MDC context was not being applied consistently in task/flow logs after upgrade to v1.0. When using logback config with JSON appenders, only the "Hello World" log (from task execution within ) got the MDC context, while the wrapper logs from , , and didn't include the MDC context.
-
Assistant
Let me check the git diff to see the final changes made to the Logs.java file.
Assistant
The fix is complete. Let me provide a summary of the changes:
Summary
Issue
MDC (Mapped Diagnostic Context) context was not being applied consistently in task/flow/execution logs after upgrading to v1.0. Only logs from
RunContextLoggerhad MDC context, while logs from theLogs.javautility class (logExecution,logTaskRun,logTrigger) did not.Root Cause
The
Logs.javautility class was usingLoggerFactory.getLogger()directly without setting the MDC context. TheRunContextLoggermechanism properly sets MDC context usingloggerContext.getMDCAdapter().setContextMap(), but theLogs.javaclass bypassed this mechanism.Fix Applied
Modified
core/src/main/java/io/kestra/core/utils/Logs.javato:- Import
org.slf4j.MDCandjava.util.Map
- Import
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.