如何从 Xamarin 中的 xml 配置加载自定义 NLog 目标?

How to load custom NLog target from xml config in Xamarin?

我有 Xamain 本机应用程序,其中 NLog 用于日志记录。 NLog配置存储在xml文件中,也就是Embedded Resource。

问题: 自定义目标未从 NLog xml 配置文件加载,但标准 NLog 目标加载正常(下面示例中的控制台目标)。

如果我在 .Net Core 控制台应用程序中放入完全相同的代码,一切正常。 我错过了什么?

自定义目标:

[Target("MyCustomTarget")]
public class CustomTargetWithLayout : TargetWithLayout
{
    protected override void Write(LogEventInfo logEvent)
    {
        var logMessage = this.RenderLogEvent(this.Layout, logEvent);
        //TODO: write rendered message by custom logic
    }
}

配置:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <targets>
    <target name="console" type="Console" />
    <target name="customTarget" xsi:type="MyCustomTarget" />
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="customTarget" />
  </rules>
</nlog>

通过以下代码加载配置:

var embeddedResourceStream = 
    Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("MyAppNamespace.NLogConfig.xml");

if (embeddedResourceStream != null)
{
    var xmlReader = System.Xml.XmlReader.Create(embeddedResourceStream);
    LogManager.Configuration = new XmlLoggingConfiguration(xmlReader, null);
}
// Only console target loaded in LogManager.Configuration.AllTargets 

自动加载扩展并不总是有效。也许你在 NLog.config:

中遗漏了这个
  <extensions> 
    <add assembly="MyCustomAssembly"/> 
  </extensions> 

也许试试这个来防止 AOT-Linker 删除任何未引用的内容:

[assembly: Preserve(typeof(MyCustomNameSpace.CustomTargetWithLayout), AllMembers = true)]

NLog 版本。 4.6 默认包含此程序集属性(但它仅适用于 NLog.dll 中的 类)。另见:https://github.com/NLog/NLog/pull/3039

或者您可以手动注册目标(在分配 Logger 或加载 NLog-config 之前):

NLog.Target.Register<MyCustomNameSpace.CustomTargetWithLayout>("MyFirst");

另请参阅:https://github.com/NLog/NLog/wiki/Register-your-custom-component