How to write an NLog target using Signalr

时光总嘲笑我的痴心妄想 提交于 2019-12-22 08:29:45

问题


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

}

回答1:


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.



来源:https://stackoverflow.com/questions/9472162/how-to-write-an-nlog-target-using-signalr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!