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 and understanding the issue better.
Assistant
The command didn't return any output. Let me try a different approach to find the LogService.java file.
Assistant
Let me explore the core directory and find the LogService.java file.
Assistant
I don't see a LogService.java file in that directory. Let me search for it more broadly.
Assistant
Let me search for any file that might be related to logging with MDC context:
Assistant
Assistant
Good! Let me also search for any logging service files:
Assistant
Let me check the Logs.java file and RunContextLogger.java which seem to be the key files:
Assistant
Now let me check the RunContextLogger.java file:
Assistant
Now I can see the issue! The
RunContextLoggerclass sets the MDC context map during logger initialization (initializeLogger()method at line ~177), but it only does this once when the logger is first created. The issue is that this MDC context is set on the logger's context, but when logs are forwarded via theForwardAppender, those logs don't have the MDC context applied because the forward appender uses a different logger that doesn't have the MDC context set.Let me check what
logEntry.toMap()returns:Assistant
Now let me check the issue more closely. The problem is in the
ForwardAppenderclass. When it forwards logs, it creates a newLoggingEventin thetransform()method, but it doesn't copy over the MDC context. Let me look at the transform method more closely and understand the flow:Assistant
Now I see the issue! The
transform()method creates a newLoggingEventbut doesn't copy the MDC property map from the original event. This means when theForwardAppenderforwards the log, the MDC context is lost.Let me check if the original event has the MDC properties:
Assistant
Now let me look at the logback documentation for
LoggingEvent. The issue is that thetransform()method inBaseAppendercreates a newLoggingEventbut doesn't copy the MDC properties. Let me verify this is the fix by looking at the LoggingEvent constructor and method for setting MDC:Assistant
Let me check the test file for Logs to understand the expected behavior:
Assistant
Let me also look at the RunContext tests to understand the expected behavior:
Assistant
Let me check the RunContextLoggerTest to understand how MDC context should be tested:
Assistant
Now let me understand the issue better. Looking at the code:
- In
RunContextLogger.initializeLogger(), the MDC context is set on the logger context vialoggerContext.getMDCAdapter().setContextMap(this.logEntry.toMap()); - When a log event is created and passed through the
BaseAppender.transform()method, a newLoggingEventis created but the MDC properties from the original event are not copied.
The issue is that when the
ForwardAppenderforwards logs to the server's root logger, the transformedLoggingEventdoesn't have the MDC context, so the logs that go to the console (via the root logger's appenders) don't include the MDC context fields liketenantId,namespace,flowId,executionId, etc.Let me check how logback's
LoggingEventhandles MDC properties:- In
Assistant
The fix is to copy the MDC property map from the original event to the new
LoggingEventin thetransform()method. TheLoggingEventclass has asetMDCPropertyMap()method that can be used for this purpose.Let me open the RunContextLogger.java file and make the fix:
Assistant
I found the issue. In the
transform()method ofBaseAppender, a newLoggingEventis created but the MDC properties from the original event are not copied to the new event. This means when theForwardAppenderforwards logs to the server's root logger, the MDC context is lost.Let me continue scrolling to see the full transform method.
Assistant
Now I can see the full
transform()method (lines 315-346). The issue is that after creating the newLoggingEventobject (lle), the code doesn't copy the MDC property map from the original event to the new one. I need to add a line to copy the MDC properties.Let me now make the fix:
Assistant
Good, the fix has been applied. The change adds
lle.setMDCPropertyMap(event.getMDCPropertyMap());after creating the newLoggingEventobject. This ensures that when logs are transformed (for secret replacement) and then forwarded viaForwardAppender, the MDC context (containingtenantId,namespace,flowId,executionId,taskId,taskRunId, etc.) is preserved.Now let me verify the fix by checking if there are any tests I can run to validate this change:
Assistant
Wait, I need to reconsider. The test passed but let me re-examine the issue more carefully. The user reported that logs from the executor/worker (like
execution.gnu_170208andtask.gnu_170208.hello) don't have MDC context, while only theflow.gnu_170208.hellologger (which usesRunContextLogger) has MDC context.Let me check the
Logs.javautility class more carefully:Assistant
I see now! The issue is that the
Logs.javautility class uses the standard SLF4J logging API and logs context information in the message itself (like[tenant: main] [namespace: company.team] [flow: gnu_170208]), but it doesn't set the MDC context. So when these logs go through logback's appenders that use MDC (like the GCP JSON layout), the MDC context fields are not present.Looking at the user's issue description again, they say:
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
This suggests there was a
LogService.javafile that used to set MDC context, but it seems like this was refactored into theLogs.javautility class and the MDC setting was lost.The fix should be to set the MDC context before logging in the
Logs.javautility methods, and then clear it after. Let me look at the issue more carefully and implement the fix:Assistant
Now I understand the issue better. The
Logs.javautility class is used by the executor/worker/scheduler components to log execution-related messages, but it doesn't set the MDC context. The user's suggestion in the issue was to addMDC.setContextMap()calls to set the context before logging.Since SLF4J's
MDCclass is framework-agnostic, I can use it directly. Let me update theLogs.javafile to set MDC context:Assistant
Now I need to modify the
Logs.javafile to set MDC context before logging. I'll use SLF4J's MDC class. The key methods that need MDC context set are:logExecution(Execution execution, Level level, String message, Object... args)- sets MDC with tenantId, namespace, flowId, executionIdlogTaskRun(TaskRun taskRun, Level level, String message, Object... args)- sets MDC with tenantId, namespace, flowId, taskId, executionId, taskRunIdlogTrigger(TriggerId trigger, Level level, String message, Object... args)- sets MDC with tenantId, namespace, flowId, triggerId
Let me update the file:
Assistant
Now I need to modify the logging methods to set MDC context. Let me update the methods that log Execution, TaskRun, and Trigger:
Assistant
I see there's a duplicate javadoc comment. Let me fix that and also update the other logging methods:
Assistant
Now I need to update the
logTriggerandlogTaskRunmethods to also set MDC context:Assistant
Now let me update the
logTaskRunmethod as well:Assistant
Let me view the full file to make sure everything looks correct:
Assistant
Now let me run the tests to verify that the changes work correctly:
Assistant
The tests pass. Now let me also run the
RunContextLoggerTestto make sure my changes toRunContextLogger.java(the MDC property map fix) are also working:Assistant
All tests pass. Now let me create a simple test script to verify that MDC context is being set properly. Let me first check if there's a way to verify MDC context in the tests:
Assistant
Let me now look at the changes I made and verify them by viewing the diff:
Assistant
The changes look correct. Let me run a broader set of tests to make sure I haven't broken anything:
Assistant
All 191 tests in the
io.kestra.core.utilspackage pass. Let me also run a few more related tests to make sure nothing is broken:Assistant
There's 1 failing test. Let me check which test failed:
Assistant
Let me check the test output more directly:
Assistant
Let me check the test results more specifically:
Assistant
Let me look at the test XML results:
Assistant
Let me check which tests have actual failures:
Assistant
Let me check what this failing test is about:
Assistant
The failing test
testOutputFilesWithSpecialCharactersis failing with ajava.nio.file.InvalidPathExceptionfor Thai characters (สวัสดี&.txt). This is unrelated to my MDC changes - it's an environment/locale issue with the test infrastructure, not something caused by my code changes. This test was likely already flaky or failing before my changes.Let me verify this by checking if this test failure existed before my changes:
Assistant
The test was already failing before my changes. Let me restore my changes:
Assistant
Good, the failing test was already failing before my changes, so it's not related to my fix. Now let me run the tests specific to the files I modified to make sure my changes are working correctly:
Assistant
All 9 tests related to my changes pass. Let me now review my changes one more time and create a summary:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.