DataDog / serilog-sinks-datadog-logs

Serilog Sink that sends log events to Datadog https://www.datadoghq.com/
Apache License 2.0
60 stars 41 forks source link

Overwriting apiKey in code #107

Closed EuroEager2008 closed 10 months ago

EuroEager2008 commented 10 months ago

I want to configure the sink in appsettings.json, except for the apiKey (because of company policy and common sense). Thus I want to ovewrite the setting for apiKey during composition root. The replacement could be from Azure Key Vault or AWS Secrets Manager or similar and accessed in code before replacing. (The secret to access secrets manager is another story, but covered)

Is this possible? How? (Simple sample please) Thanks

gh123man commented 10 months ago

Pulling this from my notes, but you should be able to do something like this:

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
    .Build();

// Override the API key
configuration.GetSection("Serilog").GetSection("WriteTo").GetChildren().FirstOrDefault().GetSection("Args")["apiKey"] = "SOME_API_KEY";

// Override the API key (alternative) - same as above, but shorter
configuration["Serilog:WriteTo:1:Args:apiKey"] = "SOME_API_KEY";

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .CreateLogger();

Let me know if this works for you.

EuroEager2008 commented 10 months ago

Thanks a lot, works great (if done just before WebApplicationBuilder.Build() is called)