Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从appsettings.json获取Nlog值_C#_Asp.net Core_.net Core_Nlog - Fatal编程技术网

C# 从appsettings.json获取Nlog值

C# 从appsettings.json获取Nlog值,c#,asp.net-core,.net-core,nlog,C#,Asp.net Core,.net Core,Nlog,我的目标是将appsettings.json中的值注入ASP.NET核心应用程序的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

我的目标是将appsettings.json中的值注入ASP.NET核心应用程序的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>
   // 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;
        }
startup.cs的片段

<!-- 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>
   // 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();
        }
    }
公共类程序
{
公共静态void Main(字符串[]args)
{
BuildWebHost(args.Run();
}
公共静态IWebHost BuildWebHost(字符串[]args)
{
返回WebHost.CreateDefaultBuilder(args)
.UseStartup()
.ConfigureLogging(日志=>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.logging.LogLevel.Trace);
})
.UseNLog()
.Build();
}
}
来自

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

要使用
${configsetting}
手动注册Microsoft扩展
i配置

IConfigurationRoot config=new ConfigurationBuilder()
.AddJsonFile(路径:“AppSettings.json”).Build();
NLog.Extensions.Logging.ConfigSettingLayoutRenderer.DefaultConfiguration=config;

更新,此处演示案例

如果您阅读了NLog ConfigSetting Layout Renderer的文档:那么您可以阅读它,如果调用
UseNLog()
,它将只起到开箱即用的作用。如果您正朝自己的方向游动,那么您必须直接在代码中分配
默认配置
。您是否可以提供一个指向包含程序集
Log.Mongo
的nuget包的链接,或者是否拼写错误了
?这是一个拼写错误,但结果是相同的。我刚刚尝试了将变量设置与您的appsettings.json,对我来说解析很好。所以我想你必须启用NLog内部记录器,看看你做错了什么:所以我在上面的帖子中添加了Program.cs文件,仍然不起作用。我是否需要为NLog执行任何其他操作,以了解它需要解析并替换NLog.config文件中的设置。它尝试将日志发送到已配置的Mongo目标,但连接字符串仍然是“mongodb://${logDatabaseUser}:${logDatabasePassword}@${logDatabase}/myApplicationDB?authSource=admin”。只需在
ConfigureNLog
中添加这些行,所以我修改了它,但我仍然得到的错误是连接字符串“${logConnectionString}”无效。是否有一个工作示例显示我们可以将appsettings.json中的值直接注入变量?我已经尝试了很多方法,但我似乎无法让它继续下去。我的应用程序是.NET Core 2.0。@user95488在这里创建了演示。在我的机器上工作。确保更新正确的nlog.config(生成将其复制到bin)