NLog


  NLog 是一个基于 .NET 平台编写的类库,我们可以使用 NLog 在应用程序中添加极为完善的跟踪调试代码。Fireasy 提供了 NLog 对 日志管理器 的实现。

  修改配置文件如下:

  • .Net Framework 下的 app.config 或 web.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="fireasy">
      <section name="loggings" type="Fireasy.Common.Logging.Configuration.LoggingConfigurationSectionHandler, Fireasy.Common"/>
    </sectionGroup>
  </configSections>
  <fireasy>
    <loggings managed="Fireasy.NLog.LogFactory, Fireasy.NLog">
      <!--<logging name="nlog" type="Fireasy.NLog.Logger, Fireasy.NLog" />-->
    </loggings>
  </fireasy>
</configuration>
  • .Net Core 下的 appsettings.json 文件
{
  "fireasy": {
    "loggings": {
      "settings": {
        "nlog": {
          "type": "Fireasy.NLog.LogFactory, Fireasy.NLog"
        }
      }
    }
  }
}

  在 .Net Core 应用中可以使用扩展方法 AddNLogger 切换到 NLog 日志组件。如下所示:

namespace demo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddFireasy().AddNLogger(s => 
            {
                s.XmlFile = "mynlog.confg";
            });
        }
    }
}

  NLog 默认使用 NLog.config 配置文件,你可以由以上的参数设置自定义配置文件。以下是 NLog.config 文件的示例:

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" 
      internalLogFile="c:    emp
log-internal.log">
  <variable name="myvar" value="myvalue"/>
  <targets>
    <target xsi:type="File" name="simpleDemoFile" fileName="Logs/SimpleDemo.txt" layout="${message}" encoding="UTF-8"/>
    <target xsi:type="Console" name="console" layout="时间:${longdate} 级别:${level} 消息:${message}" />
  </targets>
  <rules>
    <logger writeTo="simpleDemoFile"/>
  </rules>
</nlog>