Search code examples
c#.netdockerelasticsearchapm

How to read Elastic APM configuration from Environment Variables in dotnet 6+


Currently I have a dockerized WebAPI using DotNet 6 with the minimal API syntax. I have the following appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Elastic.Apm": "Trace",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ElasticApm": {
    "ServerUrls": "http://host.docker.internal:8200",
    "CaptureBody": "all",
    "CaptureBodyContentTypes": "application/x-www-form-urlencoded*, text/*, application/json*, application/xml*",
    "CloudProvider": "none",
    "ServiceName": "MyApp"
  }
}

and use it like this in my Program.cs:

...
app.UseOpenApi();
app.UseSwaggerUi3();
app.UseReDoc();

app.UseAllElasticApm(app.Configuration);

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

However, I want to pass the configuration for Elastic APM as Environment Variables.

I expect there to be some sort of way to pass configuration in any other way than appsettings.json


Solution

  • I found one way to achieve this is to create a new ConfigurationBuilder like this:

    ...
    // Setting environment variables here for readability
    Environment.SetEnvironmentVariable("ELASTIC_APM_SERVER_URLS", "http://host.docker.internal:8200");
    Environment.SetEnvironmentVariable("ELASTIC_APM_ENVIRONMENT", "dev");
    Environment.SetEnvironmentVariable("ELASTIC_APM_SERVICE_NAME", "MyApp");
    
    var config = new ConfigurationBuilder()
        .AddEnvironmentVariables()                    // Add Environment Variables to configuration 
        .Build();
    app.UseAllElasticApm(config);
    
    app.UseHttpsRedirection();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
    

    So my takeaway is that I did not understand well enough how exactly the minimal API syntax works. This way you can also use other ways such as an .env file to read the config from. These are all the Environment variables for APM:

    https://www.elastic.co/guide/en/apm/agent/dotnet/current/config-all-options-summary.html

    In summary, everything was in the docs and if you are well versed in dotnet it may be obvious, but to me it wasn't...