Logger - NeoSOFT-Technologies/rest-dot-net-core GitHub Wiki
Serilog is a third-party logging library that plugs into the default ILogger of our application with its own implementations. It enables the developers to log the events into various destinations like console, file, database, and more. Serilog supports structured logging, which allows more details and information about the event to be logged. With structured logging in place, you could use these logs to debug in a very logical way.
- Serilog.AspNetCore — Serilog support for ASP.NET Core logging(Main package)
- Microsoft.Extensions.Logging.Abstractions - Logging abstractions for Microsoft.Extensions.Logging.
- Serilog - Simple .NET logging with fully-structured events
- Serilog.Settings.Configuration — Microsoft.Extensions.Configuration (appsettings.json) support for Serilog
- Serilog.Sinks.File — Write Serilog events to text files in plain or JSON format.
- Serilog.Extensions.Logging - Low-level Serilog provider for Microsoft.Extensions.Logging
Navigate to appsettings.json and update the settings for the sinks. E.g. the Logs will be logged in the logs folder of our application.
"AllowedHosts": "*",
"Serilog": {
"Using": [],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "Logs/log-.txt",
"rollingInterval": "Day",
"restrictedToMinimumLevel": "Information",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
}
]
}
Now, we will need to configure Serilog at the entry point of our Application, ie, the Program.cs file. Navigate to Program.cs and make the following changes,
public class Program
{
public async static Task Main(string[] args)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile(
$"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
optional: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var loggerFactory = services.GetRequiredService<ILoggerFactory>();
try
{
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
await Identity.Seed.UserCreator.SeedAsync(userManager);
Log.Information("Application Starting");
}
catch (Exception ex)
{
Log.Warning(ex, "An error occured while starting the application");
}
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Demo video to get the clear result view of above implemented module.