Master_T
Master_T

Reputation: 7987

NLog in ASP.NET Core: how to inject a logger with a specific property

I'm developing an ASP.NET Core (.NET 8) web application where I'm using NLog as my logging library.

I have a service in my application where I want the logger to output to a specific file instead of the main log file, dependent upon a property in my service instance.

I've setup my logging config with a target that has a dynamic output path based on a variable, like this:

<target name="taskLogs" xsi:type="File"
        fileName="C:/myTasks/Task_Run_${event-properties:item=RunId}.log"
/>

However, I do not know how to set the RunId property value for a specific instance of the logger. Ideally I'd want to do something like this:

public MyService(ILogger logger, MyContext ctx)
{
    logger.SetProperty("RunId", ctx.RunId);
}

but I can't find something like this using NLog, all I find online and here on other questions is how to set a property globally, by invoking NLog.MappedDiagnosticsLogicalContext.Set but that is not good for me, because if I create multiple instances of MyService they would overwrite each other, right? Or am I missing something here?

Upvotes: 0

Views: 48

Answers (0)

Related Questions