如何创建一个完整的NLog日志的副本?



我正在用NLog在一个项目中替换log4net。我想支持复制记录器及其所有appender的选项。这是当前用于创建日志记录器的log4net实现。

public static ILog CreateAddonLog(string addon)
{
XmlConfigurator.Configure(new FileInfo(GetLogFilePath()));
if (string.IsNullOrEmpty(addon))
{
return LogManager.GetLogger(DEFAULT_ADDON);
}
else
{
return GetOrCreateRepostitory(addon, DEFAULT_ADDON);
}
}

创建基本附加组件日志记录器的副本:

private static ILog GetOrCreateRepostitory(string name, string sourceLogger)
{
var repoName = $"{sourceLogger}{name}";
if (LogManager.GetAllRepositories().Any(r => r.Name.Equals(repoName)))
{
return LogManager.GetLogger(repoName, repoName);
}
var repository = LogManager.CreateRepository(repoName);
var repo = (Hierarchy)repository;
CloneAppenders(name, sourceLogger).ForEach(a =>
{
repo.Root.AddAppender(a);
repo.Root.Level = ((Hierarchy)LogManager.GetRepository()).Root.Level;
BasicConfigurator.Configure(repository, a);
});
repo.Configured = true;
return LogManager.GetLogger(repoName, repoName);
}

克隆所有appender:

private static List<IAppender> CloneAppenders(string instanceName, string sourceLogger)
{
var source = LogManager.GetLogger(sourceLogger);
var appenders = source.Logger.Repository.GetAppenders()
.Where(a => a.Name.EndsWith(sourceLogger))
.ToList();
var result = appenders.Select(a =>
{
if (a is EventLogAppender src)
{
var clone = new EventLogAppender
{
ApplicationName = $"{src.ApplicationName}-{instanceName}",
LogName = src.LogName,
Layout = src.Layout,
MachineName = src.MachineName,
Name = $"{src.Name}{instanceName}",
Threshold = src.Threshold
};
if (src.FilterHead != null)
{
clone.AddFilter(src.FilterHead);
}
clone.ActivateOptions();
return clone;
}
else
{
return a;
}
});
return result.ToList();
}

像这样的事情在NLog中是可能的吗?

认为所有plugin-addons应该共享相同的LogManager-configuration(因为你当前解决方案执行浅克隆log4net输出源):

public static ILogger CreateAddonLog(string addon)
{
if (string.IsNullOrEmpty(addon))
{
return LogManager.GetLogger(DEFAULT_ADDON);
}
else
{
return LogManager.GetLogger(addon).WithProperty("PluginName", addon);
}
}

然后像这样定义EventLog-target:

<targets>
<target xsi:type="EventLog"
name="EventLog"
source="ApplicationName-${event-properties:PluginName:whenEmpty=Core}" />
</targets>

参见:https://github.com/NLog/NLog/wiki/Eventlog-target

相关内容

  • 没有找到相关文章

最新更新