๐Ÿ˜œ

์ญˆ๋‚˜์•„๋น  ๋ธ”๋กœ๊ทธ

JUNA
STUDIO

[C#][NLog] Creating a Callback Function That is Called Every Time a Log Message is Generated

๋ฐœํ–‰์ผ: Jan, 2025
์กฐํšŒ์ˆ˜: 1
๋‹จ์–ด์ˆ˜: 101

Table of Contents

Introduction

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.

Implementation with MethodCallTarget

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

Example

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

References

For more information, please visit the NLog MethodCallTarget Documentation.

Tags: #NLog#logging#MethodCallTarget#GRPC#WebSocket#Kafka
JUNA BLOG VISITORS
Today
7
 (
updown
-7
)
Total
657
 (
updown
+7
)

ยฉ 2025 juniyunapapa@gmail.com.