How to write an NLog target using Signalr

2019-05-09 08:59发布

I'm trying to write a target for NLog to send messages out to connected clients using SignalR.

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

}

标签: nlog signalr
1条回答
ゆ 、 Hurt°
2楼-- · 2019-05-09 09:34

I ended up with the basic the same basic structure that I started with. Just a few tweaks to get the information I needed.

  • Added exception details.
  • Html encoded the final message.

[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.

查看更多
登录 后发表回答