What is Serilog, how is it used?
First, let's install these two packages. Nuget
Install-Package Serilog.AspNetCore -Version 3.4.0
Install-Package Serilog.Sinks.File -Version 4.1.0
Open Startup.cs and make the following configurations.
public void ConfigureServices(IServiceCollection services)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Warning()
.Enrich.FromLogContext()
.WriteTo.Debug(new RenderedCompactJsonFormatter())
.WriteTo.File(Path.Combine("logs", "logs.txt"), rollingInterval: RollingInterval.Day)
.WriteTo.Console()
.CreateLogger();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSerilogRequestLogging(options =>
{
// Customize the message template
options.MessageTemplate = "Handled {RequestPath}";
// Emit debug-level events instead of the defaults
options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Debug;
// Attach additional properties to the request completion event
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
};
});
}
Things to do in Program.cs.
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace Project.UI
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
After doing these configurations, remove all records belonging to Logging section in appsettings.json. According to the structure we have realized above. Your logs will be saved daily under the logs folder. You can change the scope of logging by changing the MinimumLevel.Warning level.
Log.Warning("System Warning");
Log.Information("System Information");
Log.Fatal(new Exception("Test Error"), "System Exception");
Place the codes above in HomeController. Run your project and look at the console records and changes in the logs folder. When you see the result, you will have realized what you can do.
Good work..