努力在 .Net 6 Web 中添加自定义 NLog 布局渲染器 API

Struggling to add custom NLog layout renderer in .Net 6 Web API

我有一个 .Net 6 Web API。我使用 NLog 进行日志记录。我正在尝试使用 NLog 记录自定义字段,但我正在努力让它工作。我正在关注这个示例:https://nlog-project.org/2015/06/30/extending-nlog-is-easy.html.

所以我的 nlog.config 目前看起来像这样(我只是显示数据库目标,因为这是我认为唯一相关的部分):

<target name="db"
            xsi:type="Database"
            dbProvider="MySqlConnector.MySqlConnection, MySqlConnector"
            connectionString="some_connection_string"
            commandType="StoredProcedure"
            commandText="`abc`.`InsertLog`"
        >
            <parameter name="machineName"    layout="${machinename}" />
            <parameter name="logged"         layout="${date}" />
            <parameter name="logLevel"       layout="${level}" />
            <parameter name="message"        layout="${message}" />
            <parameter name="logger"         layout="${logger}" />
            <parameter name="properties"     layout="${all-event-properties:separator=|}" />
            <parameter name="callsite"       layout="${callsite:fileName:true}" />
            <parameter name="exception"      layout="${exception:tostring}" />
            <parameter name="callsiteLineNumber"      layout="${callsite-linenumber}" />
            <parameter name="stackTrace"      layout="${stacktrace}" />
        </target>

db 目标基本上调用了一个 MySql 存储过程。

现在我想保存一个额外的自定义字段,所以我在结束标记之前添加了这一行:

  <parameter name="newField"      layout="${newField}" />

(我也在MySql存储过程中添加了相关字段)

然后我新建一个class,继承自LayoutRenderer:

using NLog;
using NLog.LayoutRenderers;

using System;
using System.Text;

namespace PropWorx.API
{
    [LayoutRenderer("newField")]
    public class NLogLayoutRenderer : LayoutRenderer
    {
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            builder.Append("test");
        }
    }
}

我不确定这是否是我所需要的?因为它不起作用。当我尝试启动 API:

时出现此错误

NLogConfigurationException: Error when setting property 'Layout' on DatabaseParameterInfo

ArgumentException: LayoutRenderer cannot be found: 'newField'

这发生在我的 Program.cs 文件的第一行:

    public static void Main(string[] args)
    {
        // Exception is thrown on the following line:
        NLog.Logger logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Info("Init main");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception exception)
        {
            logger.Error(exception, "Stopped program because of exception");
            throw;
        }
        finally
        {
            NLog.LogManager.Shutdown();
        }
    }
    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
            logging.SetMinimumLevel(LogLevel.Trace);
        })
        .UseNLog();
    }

有什么我哪里出错的想法吗?谢谢

替换此行:

NLog.Logger logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

这一行:

NLog.Logger logger = NLog.LogManager.Setup().SetupExtensions(s =>
   s.RegisterLayoutRenderer<PropWorx.API.NLogLayoutRenderer>("newField")
).LoadConfigurationFromAppSettings().GetCurrentClassLogger();

另请参阅:https://github.com/NLog/NLog/wiki/Register-your-custom-component#register-nlog-extensions-from-assembly-at-runtime

另请参阅:https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-6#3-update-programcs