Skip to content

Instantly share code, notes, and snippets.

@OndrejValenta
Last active October 24, 2020 22:31
Show Gist options
  • Save OndrejValenta/aa041e3e975e1e1d1879cbeab4f9576c to your computer and use it in GitHub Desktop.
Save OndrejValenta/aa041e3e975e1e1d1879cbeab4f9576c to your computer and use it in GitHub Desktop.

Serilog configuration for easy console/file/debug logging in Console apps

Using Microsoft Logging extensions

Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
Serilog.Debugging.SelfLog.Enable(Console.Error);

loggerConfig = new LoggerConfiguration()
  .MinimumLevel.Verbose();

loggerConfig
  .WriteTo.Debug(outputTemplate: "[{Timestamp:HH:mm:ss.fff} {Level:u3}] | {Message:lj}{NewLine}{Exception}") // defined in Serilog.Sinks.Debug assembly.
  .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss.fff} {Level:u3}] | {Message:lj}{NewLine}{Exception}")
  .WriteTo.File($"run.log", rollingInterval: Serilog.RollingInterval.Day);

loggerFactory = (ILoggerFactory)new LoggerFactory();
Log.Logger = loggerConfig.CreateLogger();
loggerFactory.AddSerilog(Log.Logger);

logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation("Logger initialized");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment