1

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.
Mark Cilia Vincenti
  • 1,410
  • 8
  • 25
  • You can use [NLog Layout](https://github.com/NLog/NLog/wiki/Layouts) for Email-Target-Configuration, so NLog.config lookup configuration values. Ex. using [${configsetting}](https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer) or [${appsetting}](https://github.com/NLog/NLog/wiki/AppSetting-Layout-Renderer) – Rolf Kristensen Jan 19 '23 at 16:33
  • Notice `SimpleConfigurator.ConfigureForTargetLogging` discards the existing NLog-configuration, and replaces with new configuration containing only the specified target. If you insist on doing the mix, then I suggest doing this `NLog.LogManager.Setup().LoadConfigurationFromFile().LoadConfiguration(configBuilder => )` and then adjust the NLog-configuration further using the `configBuilder`. See also: https://github.com/NLog/NLog/wiki/Fluent-Configuration-API – Rolf Kristensen Jan 19 '23 at 16:37

1 Answers1

2

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.

Mark Cilia Vincenti
  • 1,410
  • 8
  • 25