代码和配置文件中的NLog配置



我有NLog代码当前从NLog读取。配置设置日志到文本文件,然后我想添加日志致命错误到电子邮件。但是,电子邮件设置在我的应用程序设置中。json文件。

我到目前为止尝试的是在我的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);

然而,当我尝试_logger.Fatal("testing, please ignore");时,我有2个问题:

  1. _logger.Factory.Configuration.AllTargets下,我现在只看到我上面配置的邮件设置,我理解这是由于simpleconfigator覆盖(但我不确定我需要做什么,以便我添加而不是覆盖)。
  2. 我仍然没有收到电子邮件,尽管我不知道我现在如何调试这个。

我修复了这两个问题。

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();

第一个问题与最后3行有关,而第二个问题与SMTP配置有关。

最新更新