NLog configuration from both code and config file

249 views Asked by At

I have NLog code currently reading from NLog.config to set up logging to text files and then I'd like to add logging fatal errors to email. However, the email settings are in my appsettings.json file.

What I tried so far is this in my Startup.cs

var emailConfig = Configuration
    .GetSection("EmailConfiguration")
    .Get<EmailConfiguration>();
services.AddSingleton(emailConfig);

var mailTarget = new MailTarget()
{
    SmtpServer = emailConfig.SmtpServer,
    SmtpUserName = emailConfig.UserName,
    SmtpPort = emailConfig.Port,
    SmtpPassword = services.BuildServiceProvider().CreateScope().ServiceProvider.GetService<IEmailSender>().Decrypt(emailConfig.Password),
    To = emailConfig.To
};

NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(mailTarget, LogLevel.Fatal);

However I have 2 problems when I try to _logger.Fatal("testing, please ignore");:

  1. Under _logger.Factory.Configuration.AllTargets I now only see the mail settings I configured above, which I understand is due to SimpleConfigurator overwriting (yet I'm not sure what I need to do so that I add rather than overwrite).
  2. I still didn't receive an email despite and I'm not sure how I can debug this now.
1

There are 1 answers

0
Mark Cilia Vincenti On

I fixed both issues.

var mailTarget = new MailTarget()
{
    SmtpServer = emailConfig.SmtpServer,
    SmtpUserName = emailConfig.UserName,
    SmtpPort = emailConfig.Port,
    SmtpPassword = services.BuildServiceProvider().CreateScope().ServiceProvider.GetService<IEmailSender>().Decrypt(emailConfig.Password),
    From = emailConfig.UserName,
    To = emailConfig.To,
    EnableSsl = true,
    SmtpAuthentication = SmtpAuthenticationMode.Basic,
    Html = true
};

var configuration = LogManager.Configuration;
configuration.AddRuleForOneLevel(LogLevel.Fatal, mailTarget);
LogManager.ReconfigExistingLoggers();

The first problem related to the last 3 lines, whereas the second issue was related to the SMTP configuration.