.net core 2.2,从用户密码中读取serilog的设置

时间:2019-05-21 11:01:10

标签: c# asp.net-core serilog asp.net-core-2.2

我已经设置好解决方案,并且serilog从appsettings.json中读取值

public void Configure(IApplicationBuilder application, IHostingEnvironment environment, ILoggerFactory loggerFactory)
{
     Logger log = new LoggerConfiguration()
            .ReadFrom.Configuration(Configuration)
            .CreateLogger();
     loggerFactory.AddSerilog(log);

应用设置如下:

 "Serilog": {
    "Using": [ "Serilog.Sinks.Slack", "Serilog.Sinks.ApplicationInsights" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Error",
        "System": "Error"
      }

    },
    "WriteTo": [
      {
        "Name": "Slack",
        "Args": {
          "WebHookUrl": "https://hooks.slack.com/services/xxx/yyy/zzz",
          "CustomChannel": "#channel"
        }
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "InstrumentationKey": "xxx-xxx-xxx-xxx-xxx",
          "restrictedToMinimumLevel": "Information",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ]
  }

所以直到这里一切都很好,但是我不想在我的存储库中存储诸如webhook和InstrumentationKey之类的秘密。我想从安全的地方阅读它们,例如开发环境中的用户机密和发行中的Key-vault。如何更改它以替换用户秘密的值?

https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-2.2&tabs=windows

配置是否自动被覆盖?

如果没有,我知道我可以从秘密中读取我的配置,比如说

  webHookUrl = Configuration["Serilog:WriteTo:Slack:WebHookUrl"];

但是我如何将其应用到loggerConfig?我的意思是,writeTo部分在设置中是动态的,然后我应该在代码中添加它吗? :\

更新

由于许多人提出了要求,所以在我的program.cs中,我有:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseApplicationInsights()
                .UseStartup<Startup>();

根据Microsoft文档,一切都应该正常工作,因为我拥有CreateDefaultBuilder并且正在运行.net core 2.2。 https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-2.2&tabs=windows#access-a-secret

在ASP.NET Core 2.0或更高版本中,当项目调用CreateDefaultBuilder 以预先配置的默认值初始化主机的新实例时,会在开发模式下自动添加用户密码配置源。当EnvironmentName为Development时,CreateDefaultBuilder调用AddUserSecrets。

不调用CreateDefaultBuilder时,通过在Startup构造函数中调用AddUserSecrets显式添加用户密码配置源。仅在应用程序在开发环境中运行时才调用AddUserSecrets

4 个答案:

答案 0 :(得分:1)

这是我目前用于ASP.NET Core 3.1 Web应用程序的内容。它支持appsettings.json(适用于所有环境)和Visual Studio的用户密码(secrets.json),而无需编写任何明智的信息(例如用户密码的唯一ID)代码。

Program.cs 文件的Main()方法:

public static void Main(string[] args)
{
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json",
            optional: false,
            reloadOnChange: true)
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", 
            optional: true,
            reloadOnChange: true)
        .AddUserSecrets<Startup>(optional: true, reloadOnChange: true)
        .Build();

    Log.Logger = new LoggerConfiguration()
        .WriteTo.MariaDB(
            restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information,
            connectionString: configuration.GetConnectionString("DefaultConnection"),
            tableName: "Logs",
            autoCreateTable: false,
            useBulkInsert: false,
            options: new MariaDBSinkOptions() 
            { 
                LogRecordsExpiration = new TimeSpan(90, 0, 0, 0, 0) 
            })
        .CreateLogger();

    try
    {
        Log.Information("Starting the HostBuilder...");
        CreateWebHostBuilder(args).Build().Run();
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "The HostBuilder terminated unexpectedly");
    }
    finally
    {
        Log.CloseAndFlush();
    }
}

Program.cs 文件的CreateWebHostBuilder()方法:

public static IHostBuilder CreateWebHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.ConfigureKestrel(serverOptions =>
            {
                // Set properties and call methods on options
            })
            .UseStartup<Startup>();
        })
        .UseSerilog();

如果您需要其他信息,请查看我的博客上的this post

答案 1 :(得分:0)

您可以使用IOptions来实现

首先,我需要定义模型以保存所需的信息

    public class AssetSettings
    {
        public string StorePath { get; set; }
        public string AssetPath { get; set; }
        public string GoogleDriveStorePath { get; set; }
    }

然后我需要在Startup.cs中注册配置

services.Configure<AssetSettings>(configuration.GetSection("AssetSettings"));

在我的服务中,我可以使用此配置简单地读取我的配置

private readonly IOptions<AssetSettings> _assetSettings;

public SettingsRepository(
            IOptions<AssetSettings> assetSettings)
        {
            _assetSettings = assetSettings;
        }

然后只需致电

_assetSettings.Value.StorePath

答案 2 :(得分:0)

  

我已经在秘密中复制了相同的设置,并将其从我的应用程序设置中删除,但是现在我没有收到任何日志。我想念什么吗?

如果您将serilog配置从division 0 - default (this is not in the Division table) <-- i want to add this to the select list 1 - corporate 4 - human resource 7 - engineering 移至appsettings.json,则需要修改secrets.json中的ReadFrom.Configuration()以便从secrets.json中读取。

Configure

答案 3 :(得分:0)

我认为@Crowcoder在对OP的第一条评论中是正确的。因此,您需要做的就是将appsettings.json中的结构和配置的一部分“复制”到主目录中的secrets.json文件中。

因此,在您的情况下,您将执行以下操作:

    "Serilog": {

    "WriteTo": [
      {
        "Name": "Slack",
        "Args": {
          "WebHookUrl": "https://hooks.slack.com/services/xxx/yyy/zzz"
        }
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "InstrumentationKey": "xxx-xxx-xxx-xxx-xxx"
        }
      }
    ]
  }

因此仅存在机密信息。