How to write exceptions using Serilog logging framework

Handling exception using Serilog, specifying console output, log emails, sink file etc.

 

Posted: December 20, 2019. | By: mustafa

Today we are going to use Serilog to write log emails depending on the log level to some particular email id.

Logging is always needed for every application to catch and handle exceptions. It is fundamental to troubleshoot any application problems.

Logging frameworks make it easy to send your logs to different places, Serilog uses what are called sinks to send your logs to a text file, database, or email.

How to install Serilog via Nuget Package

Starting with Serilog installing a Serilog Nuget package. You will also want to pick some logging sinks to target your log messages output, including the console and a text file and even email.

Install-Package Serilog
Install-Package Serilog.Sinks.Console

Example code -

Serilog’s sinks are configured in code when your application first starts. Here is an example:

using (var log = new LoggerConfiguration()
 .WriteTo.Console()
 .CreateLogger())
{
 log.Information("Hello, Testing Serilog!");
 log.Warning("End of Job.")
}

Now on running console application messages should display in a console window.

It is best to not send an email on every exception occurred

We can use filters to suppress certain logging statements, Serilog has the ability to specify log levels to send to specific sinks or suppress all log messages. Use the restrictedToMinimumLevel parameter.

Log.Logger = new LoggerConfiguration()
 .MinimumLevel.Debug()
 .WriteTo.File("log.txt")
 .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
 .CreateLogger();

Different log levels defined are - verbose, debug, information, warning, error, and fatal logging levels as appropriate.


related posts

Back to top