File Logging in .NET Console Apps with Serilog
Goal
Set up basic file logging in a .NET Console application using Serilog.
Setup
Install Serilog:
dotnet add package Serilog
Implementation
Configure the logger in your Main method:
static async Task Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File("logs/log.json")
.CreateLogger();
Log.Information("Running..");
}
This configuration:
- Writes logs to both console and
logs/log.json - Enriches log events with contextual information via
FromLogContext()