Adding Build Id to MDC not working properly

Hi,

I am currently trying to add the BuildId in the MDC and then to access it in the teamcity-agent-log4j.xml file.
It was working and then I realised that the Build Id was not always the right one. In the first 2 builds I have the right Build Number but after that it's not always the right one. Here is an example with build number 4. It seems to have saved some old MDC with build id 3 and 2  :

[2021-08-10 17:27:27,580]   INFO | 4 | Testteamcity_Build - ----------------------------------------- [ Step 'TestStep (Command Line)' (simpleRunner), Build "Testteamcity / Build" #4 {id=4, buildTypeId='Testteamcity_Build'} ] -----------------------------------------
[2021-08-10 17:27:27,582]   INFO | 4 | Testteamcity_Build - Starting "/opt/buildagent/temp/agentTmp/custom_script400763139097935001" in directory "/opt/buildagent/work/903868f2c04f952a"
[2021-08-10 17:27:27,585]   INFO | 3 | Testteamcity_Build - test
[2021-08-10 17:27:27,585]   INFO | 2 | Testteamcity_Build - Process exited with code 0

The .java file in the agent looks like that (without the imports):

public class AppAgent extends AgentLifeCycleAdapter {
    public AppAgent(EventDispatcher<AgentLifeCycleListener> events) {
        events.addListener(this);
    }

    @Override
    public void buildStarted(@NotNull AgentRunningBuild runningBuild)    {
MDC.clear();
MDC.put("BuildId", String.valueOf(runningBuild.getBuildId()));
MDC.put("BuildConfigurationId", runningBuild.getBuildTypeExternalId());
    }

    @Override
    public void buildFinished(@NotNull AgentRunningBuild build, @NotNull BuildFinishedStatus buildStatus)
    {
        MDC.clear();
    }
}
And a small part of my log4j.xml file where I access those values :
<appender name="ROLL.BUILD" class="jetbrains.buildServer.util.TCRollingFileAppender">
    <param name="file" value="${teamcity_logs}/teamcity-build.log"/>
    <param name="maxBackupIndex" value="1"/>
    <layout class="jetbrains.buildServer.log.MessagesFilterLayout">
      <param name="ConversionPattern" value="[%d] %6p | %X{BuildId} | %X{BuildConfigurationId} - %m%n"/>
    </layout>
  </appender>

Please sign in to leave a comment.