NLog回调可能吗? [英] NLog callback possible?
问题描述
我正在将自行开发的日志记录系统转换为NLog,并且想知道是否有办法将事件添加到Logger或以其他方式支持一种机制,当我记录消息时,可以使用最终格式化的消息和LogLevel.我目前使用类似的方法将服务器消息发送回连接的客户端.
I am in the process of converting a home grown logging system to NLog and am wondering if there is a way to add an event to a Logger or otherwise support a mechanism where when I log a message I can get a callback with the final formatted message and the LogLevel. I currently use something like this to send server messages back to a connected client.
Thx
推荐答案
这是我在评论中所讨论的内容的MCVE.创建一个接受一些回调函数的目标:
This is an MCVE of what I was talking about in the comments. Create a target that accepts some callback functions:
[Target("MyFirst")]
public sealed class MyFirstTarget : TargetWithLayout
{
private readonly Action<string>[] _callbacks;
public MyFirstTarget(params Action<string>[] callbacks)
{
_callbacks = callbacks;
}
protected override void Write(LogEventInfo logEvent)
{
foreach (var callback in _callbacks)
{
callback(logEvent.FormattedMessage);
}
}
}
配置NLog以使用目标.由于回调是在构造函数中传递的,因此我以编程方式进行了此操作.您还可以在NLog.config中配置目标,但是您的目标必须是单例,然后才能在代码中注册回调.
Configure NLog to use the target. I do this programmatically since the callbacks are passed in the constructor. You can also configure the target in the NLog.config, but your target will need to be a singleton then so you can register the callbacks in code.
class Program
{
public static void Main()
{
LogManager.Configuration.AddTarget("MyFirst", new MyFirstTarget(s => Debug.WriteLine(s)));
var logger = LogManager.GetCurrentClassLogger();
logger.Debug("test");
}
}
在没有其他NLog配置的情况下(将此代码复制到一个空项目中并添加NLog nuget包),这将向您的调试窗口发送一条消息.
With no other NLog configuration (copy this code into an empty project and add the NLog nuget package), this will emit a message to your debug window.
这篇关于NLog回调可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!