Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change dynamically file path for log files .NET Core + NLog

In my .NET Core app I use some environments and I want to do different paths to log files for every environment.

For example,

Development - c:\logs
Staging - d\apps\logs

For every environment I have config section in appsettings.{env}.json:

"LocalPaths": {
    "LogFileRootDirectory": "c:\\logs\\"
}

And part of nlog.config:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="${logFileRootDirectory}internal-nlog.txt">
    ...
</nlog>

What's the best way to implement that?

like image 965
A. Gladkiy Avatar asked Dec 04 '22 22:12

A. Gladkiy


1 Answers

You could use (NLog) variables.

e.g.

<targets>
    <target name="file" xsi:type="File"
        fileName="${var:mydir}/logfile.txt" ... >

and in C#

LogManager.Configuration.Variables["mydir"] = "c:\logs";

When you change the variable, the path is automatically changed - no reload needed.

See also the docs for ${var}

Update: you could change the LogManager.Configuration after:

env.ConfigureNLog("nlog.config");

e.g. your startup.cs could look like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
                      ILoggerFactory loggerFactory)
{
    //add NLog to ASP.NET Core
    loggerFactory.AddNLog();

    //add NLog.Web
    app.AddNLogWeb();

    //configure nlog.config in your project root. 
    env.ConfigureNLog("nlog.config");


    LogManager.Configuration.Variables["mydir"] = "c:\logs";
    ...
like image 78
Julian Avatar answered Feb 12 '23 07:02

Julian