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

Time:04-28

I have a .Net 6 Web API. I use NLog for my logging. I'm trying to log a custom field with NLog, but I am struggling to get it to work. I'm following this sample: https://nlog-project.org/2015/06/30/extending-nlog-is-easy.html.

So my nlog.config currently looks like this (I'm just showing the db target as that's the only relevant part I believe):

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

The db target basically calls a MySql Stored Proc.

Now I'd like to save an extra, custom field, so I add this line just before the closing tag:

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

( I also added the relevant field to the MySql Stored Proc)

Then I create a new class, inheriting from 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");
        }
    }
}

I'm not sure if that's all I need? Because it's not working. I get this error when I try to start up the API:

NLogConfigurationException: Error when setting property 'Layout' on DatabaseParameterInfo

ArgumentException: LayoutRenderer cannot be found: 'newField'

This happens on the very fist line of my Program.cs file:

    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();
    }

Any ideas where I;m going wrong? Thanks

CodePudding user response:

Replace this line:

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

With this line:

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

See also: https://github.com/NLog/NLog/wiki/Register-your-custom-component#register-nlog-extensions-from-assembly-at-runtime

See also: https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-6#3-update-programcs

  • Related