如何使用Signalr编写NLog目标 [英] How to write an NLog target using Signalr
问题描述
我正在尝试为NLog编写一个目标,以便使用SignalR将消息发送到连接的客户端.
I'm trying to write a target for NLog to send messages out to connected clients using SignalR.
这就是我现在所拥有的.我想知道的是我应该像这样 -or-那样使用解析连接管理器的方式,获取对中心的引用(SignalrTargetHub),调用它的SendMessage方法吗?
Here's what I have now. What I'm wondering is should I be using resolving the ConnectionManager like this -or- somehow obtain a reference to the hub (SignalrTargetHub) and call a SendMessage method on it?
这两者的性能都有影响吗?
Are there performance ramifications for either?
[Target("Signalr")]
public class SignalrTarget:TargetWithLayout
{
public SignalR.IConnectionManager ConnectionManager { get; set; }
public SignalrTarget()
{
ConnectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
}
protected override void Write(NLog.LogEventInfo logEvent)
{
dynamic clients = GetClients();
var logEventObject = new
{
Message = this.Layout.Render(logEvent),
Level = logEvent.Level.Name,
TimeStamp = logEvent.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss.fff")
};
clients.onLoggedEvent(logEventObject);
}
private dynamic GetClients()
{
return ConnectionManager.GetClients<SignalrTargetHub>();
}
}
推荐答案
我最终获得了与开始时相同的基本结构.只需进行一些调整即可获得我需要的信息.
I ended up with the basic the same basic structure that I started with. Just a few tweaks to get the information I needed.
- 添加了异常详细信息.
- HTML对最终消息进行了编码.
[Target("Signalr")]
public class SignalrTarget:TargetWithLayout
{
protected override void Write(NLog.LogEventInfo logEvent)
{
var sb = new System.Text.StringBuilder();
sb.Append(this.Layout.Render(logEvent));
if (logEvent.Exception != null)
sb.AppendLine().Append(logEvent.Exception.ToString());
var message = HttpUtility.HtmlEncode(sb.ToString());
var logEventObject = new
{
Message = message,
Logger = logEvent.LoggerName,
Level = logEvent.Level.Name,
TimeStamp = logEvent.TimeStamp.ToString("HH:mm:ss.fff")
};
GetClients().onLoggedEvent(logEventObject);
}
private dynamic GetClients()
{
return AspNetHost.DependencyResolver.Resolve<IConnectionManager>().GetClients<SignalrTargetHub>();
}
}
在我的简单测试中,它运行良好.在压力下这是否会增加任何明显的负载,仍有待观察.
In my simple testing it's working well. Still remains to be seen if this adds any significant load when under stress.
这篇关于如何使用Signalr编写NLog目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!