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 ran but produced no output, which means no file was found. Let me explore the repository structure first.
Assistant
Let me look for the LogService file that the issue mentions:
Assistant
Let me check the GitHub link mentioned in the issue. It references
LogService.java:Assistant
Let me check the Logs.java file since it seems to be the logging utility:
Assistant
Now let me look for where MDC context is being set and understand the logging flow better:
Assistant
Now let me look at the DefaultRunContext to understand how MDC is being used:
Assistant
Now let me look at the issue more carefully. The problem is that when logs are sent through the
ForwardAppender, the MDC context is not being set. Let me examine theForwardAppenderclass more closely and understand the flow:Assistant
Now I understand the issue better. Looking at
RunContextLogger.java, the MDC context is being set at line 202 on the logger context. However, when theForwardAppenderforwards logs to the main server logger (fowardLogger), it's using a different logger context (the root/global logger context) that doesn't have the MDC context set.Let me look at the
ForwardAppendermore closely:Assistant
Now I see the issue! The
ForwardAppender.append()method callsfowardLogger.callAppenders(e)but the logging eventedoesn't have the MDC context from the original logger context. The MDC context is set on theRunContextLogger's logger context but not transferred to the forwarded event.Let me also look at what
logEntry.toMap()contains:Assistant
Now I understand the full picture. The
toMap()method returns a Map with all the context fields liketenantId,namespace,flowId,taskId,executionId,taskRunId, etc. This map is set as the MDC context in theRunContextLogger's logger context (line 202).However, when the
ForwardAppenderforwards the log event to the global logger (fowardLogger), it doesn't copy the MDC context from theRunContextLogger's logger context to the new logging event. The global logger uses the root logger context, which doesn't have this MDC data.Let me check the
transformmethod and theLoggingEventconstructor to see what MDC-related data is being copied:Assistant
I can see the issue now. In the
transform()method, a newLoggingEventis created but it doesn't copy the MDC properties from the original event. Let me check the LoggingEvent constructor to see if there's a way to include MDC:Assistant
Let me check the logback LoggingEvent class constructors:
Assistant
Now let me check the LoggingEvent API to understand how to copy MDC properties:
Assistant
Now I need to understand the fix. The issue is that when creating a new
LoggingEventin thetransform()method, the MDC context from the original event is not being copied over. Let me check ifILoggingEventhas a method to get MDC properties:Assistant
Now I can see that
ILoggingEventhas agetMDCPropertyMap()method. The issue is that in thetransform()method, when creating a newLoggingEvent, the MDC properties are not being copied from the original event to the new one.Let me check what methods
LoggingEventhas for setting MDC properties:Assistant
Now let me create a test script to confirm the issue first. Let me look for existing tests that test this logging behavior:
Assistant
Now I understand the issue. The problem is that when the
ForwardAppenderforwards log events to the global logger (used for server logs), it doesn't copy the MDC properties from the original event. The MDC properties are set on theRunContextLogger's private logger context, but when creating a newLoggingEventintransform(), those properties aren't transferred.The fix is to copy the MDC properties from the original event to the new
LoggingEventin thetransform()method.Let me look at the current implementation of
transform()and understand how to add MDC copying:Assistant
Now I have a clear understanding of the issue. The problem is in the
transform()method in theBaseAppenderclass. When it creates a newLoggingEvent, it doesn't copy the MDC properties from the original event.Looking at the issue description and the code:
- The MDC context is set on the
RunContextLogger's logger context vialoggerContext.getMDCAdapter().setContextMap(this.logEntry.toMap()) - When logs are created, they have MDC properties attached
- But when
transform()creates a newLoggingEvent, it doesn't copy those MDC properties - When the
ForwardAppenderforwards the log to the global logger, those MDC properties are lost
The fix is to copy the MDC properties from the original event to the new
LoggingEventin thetransform()method. Let me check theLoggingEventAPI:- The MDC context is set on the
Assistant
Let me check the LoggingEvent class to see how to set MDC properties:
Assistant
Now let me look at how
LoggingEventcan be used to set MDC properties. TheLoggingEventclass has methods for setting MDC properties:Assistant
Let me check the logback documentation/API by looking at how the event's MDC property map is used:
Assistant
Based on my analysis:
ILoggingEventhas agetMDCPropertyMap()method that returnsMap<String, String>LoggingEventshould have a way to set MDC properties
Let me look at the logback
LoggingEventclass to see the available methods:Assistant
Let me try a different approach to understand the LoggingEvent API.
Assistant
The classpath is getting complicated. Let me try a different approach - I'll look at the logback source code or documentation online, or simply look at how MDC properties are typically set on LoggingEvent.
Based on my knowledge of logback,
LoggingEventhas agetMDCPropertyMap()method inherited fromILoggingEventand also hassetMDCPropertyMap()method to set the MDC properties. Let me verify this by searching for examples in the codebase or looking at how SLF4J/logback typically works.Actually, looking at the code more carefully, I see that the
transform()method creates a newLoggingEvent. The issue is that this new event doesn't have the MDC properties from the original event.In logback,
LoggingEventhas a method calledaddMDCPropertyMap(Map<String, String> mdcPropertyMap)that can be used to copy MDC properties.Let me now implement the fix:
Assistant
The user wants me to continue with the fix. Let me look at the transform method and add the MDC property copying to it.
Assistant
I need to add MDC property copying to the
transformmethod. The newLoggingEventshould copy the MDC properties from the original event. Let me look at how to do this.In logback,
LoggingEventhas a method to add MDC property map. I need to add something like:lle.addMDCPropertyMap(event.getMDCPropertyMap());Let me edit the file to add this line after creating the new LoggingEvent and setting the custom timestamp.
Assistant
Now I need to add a line to copy the MDC properties from the original event to the new LoggingEvent. I'll add
lle.addMDCPropertyMap(event.getMDCPropertyMap());after the custom timestamp handling.Assistant
Good, the MDC copying line was added. Now let me verify the change by looking at the full context and make sure the fix is correct:
Assistant
Now let me run the existing tests to make sure the change doesn't break anything:
Assistant
The
addMDCPropertyMapmethod doesn't exist onLoggingEvent. Let me check what methods are available for setting MDC properties on the LoggingEvent. I need to find the correct API.Assistant
I see! The method is
setMDCPropertyMap, notaddMDCPropertyMap. Let me fix that:Assistant
I need to fix the sed command syntax properly. Let me use the correct sed syntax to replace
addMDCPropertyMapwithsetMDCPropertyMap.Assistant
Now let me verify the change and run the tests to see if it compiles and passes.
Assistant
Good, the fix is now using
setMDCPropertyMapinstead ofaddMDCPropertyMap. Let me run the tests to verify the fix compiles and passes.Assistant
The tests passed (no test failures shown, only warnings). Let me verify by checking if the test actually ran successfully.
Assistant
The build was successful. But I notice the test task shows as UP-TO-DATE, which means the tests might not have actually run. Let me force the tests to run and check if they pass. Let me also look at what other tests might be related to logging to make sure I haven't broken anything.
Let me also think about the issue more carefully:
- The issue is that MDC context is not being applied consistently in task/flow logs
- The user noticed that only the actual task log message gets the MDC context, but the system logs (like "Type Log started", "Type Log completed") don't have the MDC context
- The fix I made copies MDC properties from the original event to the transformed event
But wait, I need to understand the flow better. Let me look at where these system logs come from. The issue shows:
- Logs like "Flow started", "Type Log started", "Type Log completed" have the context in the message itself (like
[tenant: main] [namespace: company.team] [flow: gnu_170208])
Assistant
All 5 tests passed. Now let me verify that my fix handles edge cases properly. I should check if
getMDCPropertyMap()can return null and add a defensive check if needed.Assistant
Looking at the existing usage in
StackdriverJsonLayout.java, it directly callsevent.getMDCPropertyMap()without null checking, which suggests the method should not return null. But to be safe, let me check the logback source code or javadoc to confirm.Assistant
The method returns a Map. In logback,
getMDCPropertyMap()typically returns an empty map rather than null. Let me check the logback core source to see if null checking is needed.Let me also check if
setMDCPropertyMapcan handle null:Assistant
Good. Now let me also think about whether my fix is complete. Looking back at the issue:
- The user reports that MDC context is not consistently applied in task/flow logs
- The user found that manually setting
MDC.setContextMap()in thelogExecutionmethod fixed the issue
But my fix is in the
RunContextLogger.transform()method, which is different from what the user suggested. Let me understand the code flow better:- When a task runs, it uses
RunContextLoggerto log messages - The
RunContextLoggerhas aForwardAppenderthat forwards logs to the server's main logger - The
ForwardAppendercallstransform()which creates a newLoggingEvent - The new
LoggingEventwas not getting the MDC properties from the original event
My fix copies the MDC properties from the original event to the new event in
transform(). This should fix the issue for logs that go through theRunContextLogger.But wait, looking at the issue more carefully, the user mentions that logs from
execution.gnu_170208andtask.gnu_170208.hellodon't have MDC context. These are system logs, not user task logs. Let me check where these logs come from.Assistant
Good, I can see that system logs use
Logs.logExecutionandLogs.logTaskRunmethods. These are separate from theRunContextLoggerfix I made. Let me examine theLogs.javafile to understand how to add MDC context for system logs as well.Assistant
I need to also fix the
Logs.javautility class to set MDC context for system logs. The current implementation embeds context information in the log message as a prefix, but doesn't set MDC properties. Let me updateLogs.javato set MDC context before logging.Assistant
The user hasn't said anything yet, but I was in the middle of implementing the fix. Let me continue with the implementation. I've already:
- Fixed
RunContextLogger.javato copy MDC properties in thetransform()method - Created an updated
Logs.javathat sets MDC context for system logs
Now I need to:
- Verify the Logs.java changes compile
- Run the tests to make sure everything works
- Check the diff to see all changes
- Fixed
Assistant
The user hasn't said anything, but I see a bash-$ prompt which means I need to continue. I was in the middle of implementing the fix for the MDC context issue. Let me continue with verifying that the changes compile and run tests.
I've made two changes:
- Fixed
RunContextLogger.javato copy MDC properties in thetransform()method - Fixed
Logs.javato set MDC context for system logs
Now I need to:
- Compile and verify the changes work
- Run the tests
- Clean up the unused import in Logs.java (java.util.Map is not used)
Let me proceed with the next steps.
- Fixed
Assistant
Good, the compilation succeeded with only warnings (no errors). Now let me clean up the unused import and run the tests.
Assistant
The user is waiting for me to continue. I was in the middle of fixing the MDC context issue. I've made two changes:
RunContextLogger.java- Added MDC property copying in thetransform()methodLogs.java- Added MDC context setting for system logs with try-finally blocks
I just removed the unused
java.util.Mapimport fromLogs.java. Now I need to:- Verify the changes compile
- Run existing tests to make sure nothing is broken
- Review all the changes
Let me continue by running the tests to validate my changes.
Assistant
The user is sending empty messages, likely waiting for me to continue. Let me check my progress:
-
I've made two changes:
RunContextLogger.java- Addedlle.setMDCPropertyMap(event.getMDCPropertyMap());to copy MDC properties in thetransform()methodLogs.java- Added MDC context setting for all system logging methods (logExecution, logTrigger, logTaskRun) with try-finally blocks
-
I removed the unused
java.util.Mapimport fromLogs.java -
I confirmed compilation succeeds
-
I still need to:
- Run existing tests to make sure nothing is broken
- Verify my changes are complete and correct
- Submit the changes
Let me run the tests now and then submit.
-
Assistant
The tests passed successfully. Let me also run the LogsTest to make sure my changes to Logs.java don't break anything.
Assistant
All tests pass. Let me do a final review of all the changes I made before submitting.
Assistant
The changes look good. Let me summarize what I've done and verify everything is working correctly:
Summary of Changes
1.
RunContextLogger.java- Added MDC property copying in the
transform()method to preserve MDC context when logs are forwarded through theForwardAppender - This ensures that when task logs are forwarded to the server's main logger, the MDC context (tenantId, namespace, flowId, executionId, taskId, taskRunId, etc.) is preserved
2.
Logs.java- Added MDC context setting for all system logging methods (
logExecution,logTrigger,logTaskRun) - Used try-finally blocks to ensure MDC context is properly cleaned up after logging
- This ensures that system logs (like "Flow started", "Type Log started", "Type Log completed") have MDC context available for log appenders
Let me run a broader test to make sure I haven't broken anything else in the codebase.
- Added MDC property copying in the
Assistant
The full test suite is taking too long. Let me just run a few more targeted tests to ensure my changes work correctly and then submit.
Assistant
Let me verify the tests passed and check the final state of my changes before submitting.
Assistant
The tests passed. The user is sending empty messages which means they're waiting for me to continue or submit. Let me review my changes once more and then submit.
I've made two key changes to fix the MDC context issue:
RunContextLogger.java: Added MDC property copying in thetransform()methodLogs.java: Added MDC context setting for all system logging methods
Let me verify the changes are correct and submit.
Assistant
I have completed my fix for the MDC context issue. Here's a summary of what I've done:
Changes Made
1.
core/src/main/java/io/kestra/core/runners/RunContextLogger.java- Added
lle.setMDCPropertyMap(event.getMDCPropertyMap());in thetransform()method - This ensures that when logs are forwarded through the
ForwardAppender, the MDC context (tenantId, namespace, flowId, executionId, taskId, taskRunId, etc.) is preserved and copied to the transformed logging event
2.
core/src/main/java/io/kestra/core/utils/Logs.java- Added MDC context setting for all system logging methods (
logExecution,logTrigger,logTaskRun) - Used try-finally blocks to ensure MDC context is properly cleaned up after logging
- This ensures that system logs (like "Flow started", "Type Log started", "Type Log completed") have MDC context available for log appenders like JSON layouts
Testing
- Added
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.