I have a Web API application written in Dot Net Core 3.1 having a health check for MongoDB. I am using AspNetCore.HealthChecks.MongoDb (2.2.2) nuget for Mongo health check. We have noticed our production logs are flooded with errors saying New MongoClient can't be added into dictionary. Could you please help?
Here is the code is written in the startup for MongoDB health check,
public void ConfigureContainer(ServiceRegistry services)
{
services.AddHealthChecks()
.AddMongoDb(config.ConnectionStrings.MongoDbContext.ThrowIfNull("MongoDbContext"),
config.AppSettings.MongoDbName.ThrowIfNull("MongoDbName"), null, null, null);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHealthChecks("/api/v1.0/health", new HealthCheckOptions()
{
ResponseWriter = WriteResponse
});
}
private static Task WriteResponse(HttpContext httpContext, HealthReport result)
{
httpContext.Response.ContentType = "application/json";
if (result.Status != HealthStatus.Healthy)
{
IReadOnlyDictionary<string, HealthReportEntry> healthResult = result.Entries;
if (healthResult != null)
{
string json = new JObject(healthResult.Select(pair =>
new JProperty(pair.Key, new JObject(
new JProperty("Status", pair.Value.Status.ToString()),
new JProperty("Description", pair.Value.Description?.ToString(CultureInfo.InvariantCulture)),
new JProperty("Exception", pair.Value.Exception?.ToString()
))))).ToString(Formatting.Indented);
Log.Error("Error: {json}", json);
return httpContext.Response.WriteAsync($"{result.Status.ToString()} {Environment.NewLine} {json}");
}
}
return httpContext.Response.WriteAsync(result.Status.ToString());
}