首页 > 解决方案 > 如何从 Xamarin 中的 xml 配置加载自定义 NLog 目标?

问题描述

我有 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 

标签: .netxamarinconfigurationnlog

解决方案


自动扩展加载并不总是有效。也许你在 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


推荐阅读