How to send log emails using Serilog framework in Asp.Net

How to write an email output using Serilog logging framework in Dotnet C#.


Posted: December 20, 2019. | By: mustafa

In an DotNet application to catch an exception and handling it to send an email for loging we use Serilog in C# console application today.

Installing Nuge Package for Serilog :

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

Here is the Serilog code example to send an email for logging with minimum exception level as Error.

Include dll library code -

using Serilog;
using Serilog.Sinks.Email;

And then add the below complete code -


Log.Logger = new LoggerConfiguration()
 .WriteTo.Email(new EmailConnectionInfo
 FromEmail = ConfigurationManager.AppSettings["FromEmail"],
 ToEmail = ConfigurationManager.AppSettings["ToEmail"],
 MailServer = ConfigurationManager.AppSettings["MailServer"],
 NetworkCredentials = new NetworkCredential
 UserName = ConfigurationManager.AppSettings["UserName"],
 Password = ConfigurationManager.AppSettings["Password"]
 EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]),
 Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]),
 EmailSubject = ConfigurationManager.AppSettings["EmailSubject"]
 }, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error, batchPostingLimit: 1)


As email sink is relying on the PeriodicBatching Sink which then writes the logs periodically for the threshold limit set in configuration.
So it is good to also specify explicitely to flush serilog sinks before your application is closing. Use Log.CloseAndFlush(); at the end of code where you are catching and writing an exception.

How to get serilog's self exception :

If an error is occurred while Serilog is attempting to send the email like some configuration issue, or error connecting to the server, etc. then Serilog just swallows it. To get the error/exception we have to add as above.


Note : EmailSink to accept a comma and or semicolon separated list of recipients for emails.
We can add a list of comma and or semicolon separated email ids for EmailConnectionInfo object property ToEmail in the code above.


related posts

Back to top