I've been working with Serilog.Sinks.Email, and I notice that (other than the fact that I don't get an email), there is no exception or anything that indicates a failure when I execute the Log statement. Even if I put in junk for the MailServer, the Log statement executes as though it were successful.
I've tried the SelfLog statement, but see nothing in my Output window from that.
Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
I've added SymbolSource (http://www.symbolsource.org/Public/Wiki/Using), and am able to step through Serilog's code, but once again, no exceptions are caught.
Does Serilog really give no indication of error, or am I missing something?
Using: .NET Framework 4.6.2, Serilog 2.8, Serilog.Sinks.Email 2.3
Sample Code:
Log.Logger = new LoggerConfiguration()
.WriteTo.Email(new EmailConnectionInfo
{
FromEmail = "xxx",
ToEmail = "xxx",
MailServer = "smtp.xxx.com",
EmailSubject = "My Test"
}
).CreateLogger();
Log.ForContext<Program>().Error("Test Number {Parm}", "1");
Writing to a Serilog logger is supposed to be a safe operation and never throw exceptions, by design, thus any exceptions that happen when sending the e-mail would only appear in the SelfLog
- in your case, it would write to the Debug
console.
Now, the reason you're not even seeing exceptions in the SelfLog
is because e-mails sent via Serilog.Sinks.Email
are sent asynchronously, and your program is terminating before the the Sink had the opportunity to send the e-mail.
Before your program terminates, you need to call Log.CloseAndFlush()
so that all logs can be sent, before the app closes.
static void Main(string[] args)
{
Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));
Log.Logger = new LoggerConfiguration()
.WriteTo.Email(...)
.CreateLogger();
try
{
Log.ForContext<Program>().Error("Test Number {Parm}", "1");
// ...
}
finally
{
Log.CloseAndFlush();
}
}
That will allow you to see the error messages you're writing via SelfLog
.
You can read more about that in the documentation: Lifecycle of Loggers.
ps: If the operation you're logging is important enough that you'd want to guarantee it succeeds (or throw exception if it doesn't) then you should use Audit Logging, i.e. Use .AuditTo.Email(...)
instead of .WriteTo.Email(...)