Generally, when using NLog to generate log messages within multiple class libraries or multiple classes, there are times when you need to process the message each time a log message occurs and display it on the GUI, or publish it to a Message Broker like GRPC, WebSocket, or Kafka.
In such cases, you can easily implement it using the MethodCallTarget class of NLog as shown below.
// Define the callback function.
var target = new MethodCallTarget("LogNotify", async (logEvent, parameters) =>
{
// Perform the desired processing here. If there are no asynchronous calls inside, remove the async above.
if (logEvent.Level > NLog.LogLevel.Debug)
{
...
}
});
// Register the callback function to be called for all log message levels.
LogManager.Configuration.AddRuleForAllLevels(target);
// Update the logger configuration.
LogManager.ReconfigExistingLoggers();
The example from the official website's documentation (https://nlog-project.org/documentation/v2.0.1/html/T_NLog_Targets_MethodCallTarget.htm) is as follows.
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();
target.ClassName = typeof(Example).AssemblyQualifiedName;
target.MethodName = "LogMethod";
target.Parameters.Add(new MethodCallParameter("${level}"));
target.Parameters.Add(new MethodCallParameter("${message}"));
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
logger.Error("error message");
}
}
For more information, please visit the NLog MethodCallTarget Documentation.
ยฉ 2025 juniyunapapa@gmail.com.