我在VB.NET 4.5 Visual Studio 2013解决方案中使用NLog 4.4.12(编写本文时的最新版本)。当我尝试检索MailTarget
以便以编程方式修改配置时(例如,设置用户的服务器详细信息,' To'地址等),我可以使用
Dim oTargets As ReadOnlyCollection(Of Targets.Target) = LogManager.Configuration.AllTargets
这将返回我配置的两个目标:DatatbaseTarget
(索引= 0,名称=" Database_Target")和MailTarget
(索引= 1,名称=&# 34; Email_Target"。)
但如果我尝试使用
Dim oTarget as Targets.Target = LogManager.Configuration.FindTargetByName("Email_Target")
或
Dim oTarget As Targets.MailTarget = LogManager.Configuration.FindTargetByName(Of Targets.MailTarget)("Email_Target")
甚至
Dim oTarget as Targets.Target = LogManager.Configuration.FindTargetByName(oTargets(1).Name)
我得到了空。
我已经在bug列表,GitHub和网上搜索了解决方案,一般都没找到,所以我可能做错了什么。但我无法看到它是什么。有没有人有任何想法?
答案 0 :(得分:3)
根据罗尔夫的回应,这里完全是问题所在。 注意:这个问题 - 或混淆 - 可能会在您阅读本文时修复。
问题是我正确创建Targets
并在其参数中包含名称值,例如:
Dim oConfig As LoggingConfiguration = New LoggingConfiguration
Dim oMailTarget As New MailTarget
With oMailTarget
.Name = "Email_Target"
.SmtpServer = "mail.mydomain.com"
.EnableSsl = True
...
oConfig.AddTarget("Email", oMailTarget)
但最后一行,我在oMailTarget
添加了可选名称(" Email"),可能会覆盖oMailTarget.Name
值。
将最后一行改为:
oConfig.AddTarget(oMailTarget)
修复了问题。
如果是我,我会转储AddTarget(Name, Target)
重载,这样如果您想要命名Target
,则必须在Target
对象本身中完成。只是我的2c。
感谢罗尔夫的帮助。
答案 1 :(得分:0)
我有一个类似的问题LogManager.Configuration.FindTargetByName
为有效的记录器(在C#中)返回null
,但(看似)原因略有不同。我正在配置这样的日志记录(根据文档):
private static void ConfigureLogging()
{
var config = new LoggingConfiguration();
var logfile = new NLog.Targets.FileTarget() { FileName = "log.txt", Name = "logfile", Layout = "${longdate} ${uppercase:${level}} ${message}" };
var logconsole = new NLog.Targets.ColoredConsoleTarget() { Name = "logconsole", Layout = "${message}" };
var logmemory = new NLog.Targets.MemoryTarget () { Name = "logmemory", Layout = "${longdate} ${uppercase:${level}} ${message}" };
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, logconsole));
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, logfile));
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, logmemory));
LogManager.Configuration = config;
}
这很好用。但是,FindTargetByName
的来电始终返回null
。我通过明确添加目标解决了这个问题:
private static void ConfigureLogging()
{
var config = new LoggingConfiguration();
var logfile = new NLog.Targets.FileTarget() { FileName = "log.txt", Name = "logfile", Layout = "${longdate} ${uppercase:${level}} ${message}" };
var logconsole = new NLog.Targets.ColoredConsoleTarget() { Name = "logconsole", Layout = "${message}" };
var logmemory = new NLog.Targets.MemoryTarget () { Name = "logmemory", Layout = "${longdate} ${uppercase:${level}} ${message}" };
config.AddTarget(logfile);
config.AddTarget(logconsole);
config.AddTarget(logmemory);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, logconsole));
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, logfile));
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, logmemory));
LogManager.Configuration = config;
}