I am using serilog in my Net 5 project and I want to set the subject dynamically in code before the email is sent. I read that from version 2.2.0 this should be possible but I can't find any example of how to do this.
this is my serilog settings
Log.Logger = new LoggerConfiguration()
.WriteTo.File(path + "TTLog_" + time + ".txt")
.WriteTo.Console(theme: SystemConsoleTheme.Literate)
.WriteTo.Email(new EmailConnectionInfo {
FromEmail = FromEmail,
ToEmail = ToEmail,
MailServer = SMTP_Server,
NetworkCredentials = new NetworkCredential {
UserName = SMTP_Username,
Password = SMTP_Password
},
EnableSsl = false,
Port = SMTP_Port,
EmailSubject = "Test Subject",
},
outputTemplate: "[{Level:u4}] {Message}{NewLine}{Exception}{Timestamp}"
).CreateLogger();
In my code I want to update the EmailSubject after the LoggerConfiguration is set. how can I do that?
Update as requested in comments:
Log.Logger = new LoggerConfiguration()
.WriteTo.File(path + "TTLog_" + time + ".txt")
.WriteTo.Console(theme: SystemConsoleTheme.Literate)
.WriteTo.Email(new EmailConnectionInfo {
FromEmail = FromEmail,
ToEmail = ToEmail,
MailServer = SMTP_Server,
NetworkCredentials = new NetworkCredential {
UserName = SMTP_Username,
Password = SMTP_Password
},
EnableSsl = false,
Port = SMTP_Port,
EmailSubject = "{Msg}"
},
outputTemplate: "[{Level:u4}] {Message}{NewLine}{Exception}{Timestamp}"
).Enrich.FromLogContext()
.CreateLogger();
then if I use this it works, the email subject is "TT Log - Updated A"
string x = "A";
Serilog.Context.LogContext.PushProperty("Msg", "TT Log - Updated " + x);
but if I do this it does not work, the message subject is empty
string x = "A";
Log.Information("Test");
Serilog.Context.LogContext.PushProperty("Msg", "TT Log - Updated " + x);
How do I dynamically set the email subject from anywhere in my code?