0

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());
}
Charan Ghate
  • 1,384
  • 15
  • 32
  • You don't have any problem connecting to your database right? – vasilisdmr Mar 11 '20 at 10:24
  • @vasilisdmr no, I don have any problem connecting DB, and the application is working as expected. Only the concern is that the application keeps logging this error 10 15 times every day the specific time – Charan Ghate Mar 11 '20 at 10:37

0 Answers0