如何配置 nlog 以在 FileTarget 中使用 IHostingEnvironment.ContentRootPath

Yur*_*iyP 2 nlog asp.net-core

我正在尝试为我的 asp.net 核心应用程序添加 NLog。所以我完全按照这里的描述配置它https://github.com/NLog/NLog.Extensions.Logging。我还添加了https://github.com/NLog/NLog.Web和默认配置。到目前为止一切顺利,一切都按预期工作。

现在我想将我的日志文件存储在示例c:\temp\nlog-own-${shortdate}.log中指定的硬编码文件夹中,而不是存储在取决于当前项目的文件夹中。在我以前的 ASP.NET 项目中,我使用了类似这样的东西${basedir}\App_Data\Logs\nlog-own-${shortdate}.log。现在它也可以工作,但将文件放在 bin 目录中。但我想配置将这些文件放在IHostingEnvironment.ContentRootPath文件夹中。基本上我想要这样的东西

    private static Logger Logger = LogManager.GetCurrentClassLogger();
    private IHostingEnvironment _HostingEnvironment;
    public UserController(IHostingEnvironment env)
    {
        _HostingEnvironment = env;
    }

    public IActionResult Index()
    {
        var fileTarget = Logger.Factory.Configuration.FindTargetByName<NLog.Targets.FileTarget>("ownFile-web");
        fileTarget.FileName = new SimpleLayout(
            @"${basedir}\App_Data\Logs\nlog-own-${shortdate}.log"
                .Replace("${basedir}", _HostingEnvironment.ContentRootPath)
        );
        Logger.Info("Index page says hello");

        return View(new UserListArgs());
    }
Run Code Online (Sandbox Code Playgroud)

但以更优雅的方式。

Jul*_*ian 5

像这样的东西:

更新:在 NLog 4.4 中,这可以在一行 ( LayoutRenderer.Register)

自 NLog 4.4

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
                      ILoggerFactory loggerFactory)
{

    //add NLog to ASP.NET Core
    loggerFactory.AddNLog(); 

    //needed for non-NETSTANDARD platforms: configure nlog.config in your project root
    env.ConfigureNLog("nlog.config");

    LayoutRenderer.Register("basedir", (logEvent) => env.ContentRootPath);

    ...
 }
Run Code Online (Sandbox Code Playgroud)

NLog 4.4 之前

[LayoutRenderer("basedir")]
public class AspNetCoreBaseDirLayoutRenderer : LayoutRenderer
{
    public static IHostingEnvironment Env {get;set;}

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        builder.Append(env.ContentRootPath);
    }
}
Run Code Online (Sandbox Code Playgroud)

登记:

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


      //needed for non-NETSTANDARD platforms: configure nlog.config in your project root
      env.ConfigureNLog("nlog.config");
      ...

      //overwrite ${basedir}
      AspNetCoreBaseDirLayoutRenderer.Env = env;
      ConfigurationItemFactory.Default.LayoutRenderers
          .RegisterDefinition("basedir", typeof(AspNetCoreBaseDirLayoutRenderer ));
      ...
Run Code Online (Sandbox Code Playgroud)