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

时间:2016-08-15 09:55:52

标签: asp.net-core nlog

我正在尝试为我的asp.net核心应用程序添加NLog。所以我完全按照https://github.com/NLog/NLog.Extensions.Logging中的描述对其进行了配置。我也添加了https://github.com/NLog/NLog.Web默认配置。到目前为止,一切都很顺利。

现在我想将我的日志文件存储在示例c:\temp\nlog-own-${shortdate}.log中指定的harcoded文件夹中,而不是存储在依赖于当前项目的文件夹中。在我之前的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());
    }

但是更优雅。

2 个答案:

答案 0 :(得分:4)

这样的事情:

更新:在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);

    ...
 }

在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);
    }
}

寄存器:

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

答案 1 :(得分:0)

您是否尝试过如下设置配置:

    // Step 1. Create configuration object 
    var config = new LoggingConfiguration();

    // Step 2. Create targets and add them to the configuration 
    var consoleTarget = new ColoredConsoleTarget();
    config.AddTarget("console", consoleTarget);

    var fileTarget = new FileTarget();
    config.AddTarget("file", fileTarget);

    // Step 3. Set target properties 
    consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}";
    fileTarget.FileName = "${basedir}/file.txt";
    fileTarget.Layout = "${message}";

    // Step 4. Define rules
    var rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);
    config.LoggingRules.Add(rule1);

    var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
    config.LoggingRules.Add(rule2);

    // Step 5. Activate the configuration
    LogManager.Configuration = config;

尝试覆盖setup.cs中的nlog配置。