Skip to content
Rolf Kristensen edited this page Sep 3, 2023 · 14 revisions

Calls the specified static method on each log message and passes contextual parameters to it.

Platforms Supported: All

Configuration Syntax

<targets>
  <target xsi:type="MethodCall"
          name="String"
          methodName="String"
          className="String">
    <parameter layout="Layout" name="String" type="System.Type"/><!-- repeated -->
  </target>
</targets>

Read more about using the Configuration File.

Parameters

General Options

  • name - Name of the target.

Invocation Options

  • methodName - Method name. The method must be public and static.
  • className - Class name. Do include the assembly name, e.g. "NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests"

Parameter Options

  • parameters - The array of parameters to be passed. Collection
    Each collection item is represented by <parameter /> element with the following attributes:
    • layout - Layout that should be use to calculate the value for the parameter. Layout Required.
    • name - Name of the parameter.
    • type - Type of the parameter. System.Type

Note: Since NLog 4.3 these parameters can be optional.

Examples

Configure call of lambda at runtime

Introduced with NLog ver. 4.5.8

One can make it call a user defined delegate using Configuration API:

public class Example
{
    static void Main(string[] args)
    {
        MethodCallTarget target = new MethodCallTarget("MyTarget", (logEvent, args) => Console.WriteLine(logEvent.FormattedMessage));
        NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration();
        config.AddRuleForAllLevels(target)
        NLog.LogManager.Configuration = config;

        Logger logger = LogManager.GetLogger("Example");
        logger.Info("log message");
    }
}

Or using the Fluent-Configuration-API introduced with NLog v5:

public class Example
{
    static void Main(string[] args)
    {
        var logger = LogManager.Setup().LoadConfiguration(c =>
        {
           c.ForLogger().WriteToMethodCall((logEvent, args) => Console.WriteLine(logEvent.FormattedMessage));
        }).GetCurrentClassLogger();
        logger.Info("log message");
    }
}

Configure call of static method with NLog.config

In order to send all logs to a static method, use the following configuration file:

<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
        <target name="m" xsi:type="MethodCall" className="SomeNamespace.MyClass, MyAssembly" methodName="LogMethod">
            <parameter layout="${level}" />
            <parameter layout="${message}" />
        </target>
    </targets>
 
    <rules>
        <logger name="*" minlevel="Debug" writeTo="m" />
    </rules>
</nlog>

Per the configuration, the log method needs to be called "LogMethod" be declared in "SomeNamespace.MyClass" class. The class must be compiled to MyAssembly.dll. Each parameter of the log method must correspond to <parameter /> entry in the target configuration.

namespace SomeNamespace
{
    using System;
 
    public class MyClass
    {
        public static void LogMethod(string level, string message)
        {
            Console.WriteLine("l: {0} m: {1}", level, message);
        }
    }
}

Names of parameters are not important, only their order is. The default type of each parameter is string, but it can be overridden by adding type attribute to <parameter /> element.

Configure call of static method at runtime

It is also possible to configure logging using Configuration API:

using System;
 
using NLog;
using NLog.Targets;
using System.Diagnostics;
 
public class Example
{
    public static void LogMethod(string level, string message)
    {
        Console.WriteLine("l: {0} m: {1}", level, message);
    }
 
    static void Main(string[] args)
    {
        MethodCallTarget target = new MethodCallTarget() { Name = "MyTarget" };
        target.ClassName = typeof(Example).AssemblyQualifiedName;
        target.MethodName = "LogMethod";
        target.Parameters.Add(new MethodCallParameter("${level}"));
        target.Parameters.Add(new MethodCallParameter("${message}"));
 
        NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration();
        config.AddRuleForAllLevels(target)
        NLog.LogManager.Configuration = config;
 
        Logger logger = LogManager.GetLogger("Example");
        logger.Debug("log message");
        logger.Error("error message");
    }
}
Clone this wiki locally