elasticsearch 如何在dotnet 6+中从环境变量读取弹性APM配置

drnojrws  于 2023-03-17  发布在  ElasticSearch
关注(0)|答案(1)|浏览(110)

目前,我有一个使用DotNet 6和最小API语法的停靠WebAPI。

{
  "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"
  }
}

并在我的Program.cs中这样使用它:

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

app.UseAllElasticApm(app.Configuration);

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

但是,我希望将Elastic APM的配置作为环境变量传递。
我希望有某种方法可以通过appsettings.json以外的任何其他方式传递配置

djmepvbi

djmepvbi1#

我发现实现这一点的一种方法是创建一个新的ConfigurationBuilder,如下所示:

...
// 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();

所以我的结论是,我对最小API语法的工作原理理解得不够好。这样,你也可以使用其他方法,如.env文件来读取配置。以下是APM的所有环境变量:
https://www.elastic.co/guide/en/apm/agent/dotnet/current/config-all-options-summary.html
总之,一切都在文档中,如果你精通. net这可能是显而易见的,但对我来说,它不是...

相关问题