Michael Witt
Michael Witt

Reputation: 1712

How to add a NLog custom renderer to a custom target programmatically

I'm configuring NLog programmatically with a custom target and a custom layout renderer.

If I was doing this in XML, I would have the following definition:

    <targets>
    <target name="logLambda" xsi:type="LambdaLoggerTarget" layout="${lambdalogger-json}" />
    </targets>

How can I add this layout programmatically? In my config code, I have:

        public static void Init()
        {
            var config = new NLog.Config.LoggingConfiguration();

            LayoutRenderer.Register<LambdaLoggerLayout>("lambdalogger-json");

            var lambdaTarget = new LambdaLoggerTarget
            {
                Name = "LambdaLoggerTarget",
            };
            config.AddTarget(lambdaTarget);

            config.AddRule(LogLevel.Info, LogLevel.Fatal, lambdaTarget);

            // Apply config           
            NLog.LogManager.Configuration = config;
        }

I was assuming, in my lambdaTarget instantiation, I could find a way to specify a Layout, but I haven't found that.

Thanks!

Upvotes: 0

Views: 302

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19867

You can do this:

LayoutRenderer.Register<LambdaLoggerLayout>("lambdalogger-json");

var lambdaTarget = new LambdaLoggerTarget
{
   Name = "LambdaLoggerTarget",
   Layout = "${lambdalogger-json}",
};

If your LambdaLoggerLayout inherits from AspNetLayoutRendererBase, then it will only call DoAppend if active HttpContext is found.

Upvotes: 2

Related Questions