On my Web Api Net.Core 2.2 project, I needed to use serilog and I wanted to write log on my MongoDB instance on the cloud. Serilog has written correctly on the console and file but it didn't on the MongoDB instance. Besides It didn't throw or log any errors. How can I check what happend? How can I fix it?
Thanks a lot to everybody.
It's a C# Asp.Net WebApi .Net Core 2.2 application I installed the nuget packages below: Serilog.AspNetCore (3.0.0) (with its dependecies) Serilog.Sinks.File (4.0.0) (with its dependecies) Serilog.Sinks.MongoDB (4.0.0) (with its dependecies)
My Program.cs
public class Program
{
static readonly LoggerProviderCollection Providers = new LoggerProviderCollection();
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
.WriteTo.MongoDB("mongodb://myusername:[email protected]:27017/mydbName", collectionName: "log")
.WriteTo.Providers(Providers)
.CreateLogger();
try
{
Log.Information("Starting web host");
CreateWebHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog(providers: Providers);
}
My Startup.cs
public void ConfigureServices(IServiceCollection services){
...
services.AddLogging();
...
}
public void Configure(IApplicationBuilder app, IBackgroundJobClient backgroundJobs, IHostingEnvironment env, ODataModelBuilder modelBuilder)
{
...
app.UseSerilogRequestLogging();
...
}
A simple test controller that I've used
[Route("api/[controller]")]
[ApiController]
public class ValueController : ControllerBase
{
readonly ILogger<ValueController> _logger;
public ValueController(ILogger<ValueController> logger)
{
_logger = logger;
}
[HttpGet]
public string Get()
{
_logger.LogInformation("That's all!");
return "Ok";
}
}
I've found the problem. The mongoDb credentials was wrong. I checked the problem with this useful serilog feature
Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
That show off output all serilog errors.
serilog debug guide
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With