Home > Software engineering >  How to include git's commit id in the log's filename?
How to include git's commit id in the log's filename?

Time:12-02

NLog produces the following log filename MyMachine_MyExe_1.0.0.0.log. It includes the assembly version, but not the git's commit id which can be seen in dll's Product version property below.

Is there a way, either via NLog.config or programmatically to include the git's commit id in the log's filename?

NLog.config

<variable name="callsite" value="${callsite:includeNamespace=false:className=true:methodName=true}"/>
<variable name="baseLogDir" value="logs" />
<variable name="baseLogFilename" value="${machinename}_${processname}_${assembly-version}" />
<variable name="debugTraceLayout" value="${longdate}|${level:uppercase=true}|${callsite}|${message}" />
<targets>
    <target
        xsi:type="Console"
        name="console"
        layout="${longdate}|${level:uppercase=true}|${message}" />
    <target xsi:type="File"
        name="fileInfo"
        fileName="${baseLogDir}/${baseLogFilename}.log"
        layout="${longdate}|${level:uppercase=true}|${message}"
        archiveFileName="${baseLogDir}/archive/${baseLogFilename}_{#}.log"
        archiveNumbering="Date"
        archiveOldFileOnStartup="true"
        archiveDateFormat="yyyyMMdd_HHmmss" />

MyProject.csproj

<Project Sdk="Microsoft.NET.Sdk">
    <Target Name="SetSourceRevisionId" BeforeTargets="InitializeSourceControlInformation">
        <Exec Command="git describe --long --always --dirty --exclude=* --abbrev=8" ConsoleToMSBuild="True" IgnoreExitCode="False">
            <Output PropertyName="SourceRevisionId" TaskParameter="ConsoleOutput" />
        </Exec>
    </Target>       
</Project>

MyLibrary.dll Properties

enter image description here

CodePudding user response:

I would define additional assembly attributes in your msbuild project;

<Project Sdk="Microsoft.NET.Sdk">
    <Target Name="SetSourceRevisionId" BeforeTargets="InitializeSourceControlInformation">
        <Exec ...></Exec>
        <ItemGroup>
            <AssemblyMetadata Include="SourceRevisionId" Value="$(SourceRevisionId)" />
        </ItemGroup>
    </Target>       
</Project>

Which I believe you can use to define NLog's Global Diagnostic Context (GDC)

GlobalDiagnosticsContext.Set(
    "SourceRevisionId",
    typeof(Program).Assembly
        .GetCustomAttributes<AssemblyMetadataAttribute>()
        .Where(a => a.Key == "SourceRevisionId")
        .Single()
        .Value
);

And define the output filename;

fileName="${baseLogDir}/${gdc:item=SourceRevisionId}.log"
  • Related