繁体   English   中英

从appsettings.json获取Nlog值

[英]Get Nlog values from appsettings.json

我的目标是将来自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();
        }
    }

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

NLog.Web.AspNetCoreNLog.Extensions.Hosting调用UseNLog() ,它将自动向ConfigSettingLayoutRenderer注册托管环境配置。

要使用${configsetting}手动注册Microsoft Extension 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM