【问题标题】:Get Nlog values from appsettings.json从 appsettings.json 获取 Nlog 值
【发布时间】:2019-06-24 19:53:14
【问题描述】:

我的目标是将 appsettings.json 中的值注入到 ASP.NET Core 应用程序的 nlog.config 中。我正在使用 NLog.Web.AspNetCore 4.8.3、NLog 4.6.5、NLog.config 4.6.5 和 Microsoft.Extensions.Logging.Abstractions 2.0.0。

我无法让这个工作。我的印象是 ${configsetting:name=ConnectionStrings.ApplicationDatabase} 将被替换为我的 appsettings.json 文件中的 ConnectionStrings.ApplicationDatabase 值,但事实并非如此工作。当我运行我的应用程序时,nlog.config 变量值未更改并引发错误,因为那是无效的连接字符串。

nlog.config 片段

<!-- Using logDirectory variable to set path to src/logs folder in allfile and ownFile-web targets below -->
  <variable name="logDirectory" value="${basedir}/../../../logs/${shortdate}/internal-nlog.log" />
  <variable name="logDatabase" value="${configsetting:name=ConnectionStrings.ApplicationDatabase}"/>
  <variable name="logDatabaseUser" value="${configsetting:name=DatabaseCredentials.User}"/>
  <variable name="logDatabasePassword" value="${configsetting:name=DatabaseCredentials.Password}"/>-->
  <variable name="logConnectionString" value="mongodb://${logDatabaseUser}:${logDatabasePassword}@${logDatabase}/myApplicationDB?authSource=admin"/>

  <!-- Load the ASP.NET Core plugin -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore" />
    <add assembly="NLog.Mongo" />
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="allfile" fileName="${logDirectory}"
            layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName="${logDirectory}"
            layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

    <target xsi:type="Mongo" name="error-mongo"
            connectionString="${logConnectionString}"
            collectionName="errorLogs">
      <field name="date" layout="${date}" bsonType="DateTime" />
      <field name="level" layout="${level}" />
      <field name="message" layout="${message}" />
      <field name="logger" layout="${logger}" />
      <field name="exception" layout="${exception:format=tostring}" />
      <field name="threadID" layout="${threadid}" bsonType="Int32" />
      <field name="threadName" layout="${threadname}" />
      <field name="processID" layout="${processid}" bsonType="Int32" />
      <field name="processName" layout="${processname:fullName=true}" />
      <field name="userName" layout="${windows-identity}" />
    </target>

<target xsi:type="Mongo" name="event-mongo"
         connectionString="${logConnectionString}"
         collectionName="eventLogs">
      <field name="date" layout="${date}" bsonType="DateTime" />
      <field name="level" layout="${level}" />
      <field name="event" layout="${event-properties:item=EventId.Id}" />
      <field name="message" layout="${message}" />
      <field name="logger" layout="${logger}" />
    </target>
  </targets>

appsetting.json 片段

  "ConnectionStrings": {
    "ApplicationDatabase": "App-db-server-1.com:27017,App-db-server-2.com:27017,App-db-server-3.com:27017/AccessManagement?ssl=true&replicaSet=myReplicaSet&authSource=admin"
  },
  "DatabaseCredentials": {
    "User": "",
    "Password": ""
  }
}

startup.cs 片段

   // 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)
        {
            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();

            ConfigureNLog(app, loggerFactory);

            /*These settings need to be changed*/
            app.UseCors(
                options => options
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
            );

            app.UseAuthentication();
            //Swagger Set Up
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Authentication API V1");
            });
            app.UseMvc();
        }

        private static void ConfigureNLog(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            IConfigurationRoot config = new ConfigurationBuilder()
                .AddJsonFile(path: "appSettings.json").Build();
            NLog.Extensions.Logging.ConfigSettingLayoutRenderer.DefaultConfiguration = config;
        }

**Program.cs 片段

    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                })
                .UseNLog()
                .Build();
        }
    }

【问题讨论】:

  • 如果您阅读了 NLog ConfigSetting Layout Renderer 的文档:github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer 那么您可以阅读它只有在调用 UseNLog() 时才能开箱即用。如果您按照自己的方向游泳,则必须直接在代码中分配DefaultConfiguration
  • 您能否提供指向包含程序集Log.Mongo 的nuget-package 的链接,或者您是否拼错了&lt;add assembly="NLog.Mongo" /&gt;
  • 这是一个错字,但结果是一样的。
  • 我刚刚尝试了您的变量设置和您的 appsettings.json,它对我来说解决得很好。所以我猜你必须启用 NLog 内部记录器,看看你做错了什么:github.com/NLog/NLog/wiki/Internal-Logging

标签: c# asp.net-core .net-core nlog


【解决方案1】:

来自https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer

当从NLog.Web.AspNetCoreNLog.Extensions.Hosting 调用UseNLog() 时,它会自动使用ConfigSettingLayoutRenderer 注册托管环境配置。

使用${configsetting}手动注册微软扩展IConfiguration

IConfigurationRoot config = new ConfigurationBuilder()
    .AddJsonFile(path: "AppSettings.json").Build();
NLog.Extensions.Logging.ConfigSettingLayoutRenderer.DefaultConfiguration = config;

更新,这里是演示案例https://github.com/304NotModified/NLog-Demo-cases/tree/master/AspNetCore2WithConfigSetting

【讨论】:

  • 所以我在上面的帖子中添加了 Program.cs 文件,仍然不起作用。我是否需要为 NLog 做任何其他事情才能理解它需要解析和替换 nlog.config 文件中的设置。它尝试将日志记录到配置的 Mongo 目标,但连接字符串仍然是“mongodb://${logDatabaseUser}:${logDatabasePassword}@${logDatabase}/myApplicationDB?authSource=admin”。
  • 只需将这些行添加到ConfigureNLog
  • 所以我修改了它,但我仍然得到的错误是连接字符串“${logConnectionString}”无效。是否有一个工作示例表明我们可以将 appsettings.json 中的值直接注入到变量中?我已经尝试了很多方法,但我似乎无法做到这一点。我的应用是 .NET Core 2.0。
  • @user95488 在这里创建了演示。 github.com/304NotModified/NLog-Demo-cases/tree/master/… 在我的机器上工作。一定要更新正确的nlog.config(build会复制到bin)
猜你喜欢
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 2020-06-11
  • 2018-04-07
相关资源
最近更新 更多