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

心已入冬 提交于 2021-01-29 04:15:32

问题


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?


回答1:


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";
    ...



回答2:


NLog.Extension.Logging ver. 1.4 supports ${configsetting} for reading directly from appsetting.json:

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

See also: https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer




回答3:


As they state it on their GitHub repository:

.NET Core issues:

  • ${basedir} isn't working will in .NET Core
  • LogManager.GetCurrentClassLogger() will use the filename instead of the full class name (class name and namespace, like in NLog 4). This will be fixed in the final of NLog 5 (after the release of NETSTANDARD 2.0)

So you can't do that right now. Maybe they will fix that in the future.



来源:https://stackoverflow.com/questions/42945483/change-dynamically-file-path-for-log-files-net-core-nlog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!