如何在.NET Core应用程序中配置NLog

时间:2017-11-06 22:22:53

标签: c# .net-core configuration-files nlog

我正在使用名为DataFlowEx的库,它需要NLog的配置才能输出它的调试和其他信息。

本教程使用xml文件显示配置。

我想过使用Microsoft.Extensions.Configuration,并将其指向XML,但它似乎不起作用......

这是我到目前为止所做的:

var config = new ConfigurationBuilder().AddXmlFile("app.config", true).Build();

配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="common">
      <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <common>
    <logging>
      <factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20">
        <arg key="configType" value="FILE" />
        <arg key="configFile" value="~/NLog.config" />
      </factoryAdapter>
    </logging>
  </common>
</configuration>

和nlog配置:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <variable name="logFormat" value="${date:format=yy/MM/dd HH\:mm\:ss} [${logger}].[${level}] ${message} ${exception:format=tostring} "/>

  <targets>
    <target xsi:type="Console" name="console" layout="${logFormat}"/>
    <target xsi:type="File" name ="file" fileName="Gridsum.DataflowEx.Demo.log" layout="${logFormat}" keepFileOpen="true"/>
  </targets>

  <rules>
    <logger name ="Gridsum.DataflowEx*" minlevel="Trace" writeTo="console,file"></logger>
  </rules>
</nlog>

什么都没有输出......我这样做了吗?

2 个答案:

答案 0 :(得分:3)

也许这会有所帮助:

https://github.com/net-commons/common-logging/issues/153

停止使用app.config,而是使用专用的nlog.config(请记住将nlog.config文件配置为“始终复制”)

答案 1 :(得分:1)

我在nup的所有代码在Startup.cs中都是这样的。即在Configure方法中:

    using NLog.Extensions.Logging;
    using NLog.Web;
    using Nlog;

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //setup logging
        loggerFactory.AddNLog();
        env.ConfigureNLog("nlog.config");
        app.AddNLogWeb();

        // other unrelated stuff...
    }

对于控制台应用,您不需要任何特别的东西......

using NLog;

public class Engine
{
    private readonly ILogger _logger;

    public Engine()
    {
        _logger = LogManager.GetCurrentClassLogger();
    }

    public async Task SendAsync(OutboundMessageType messageType)
    {
        _logger.Trace($"Entered SendAsync() for message type '{messageType}'.");

        // other stuff here
    }
}

以上内容仅来自我项目中的随机类。没有配置代码。我的nlog.config与可执行文件

位于同一目录中