How to write an NLog target using Signalr

徘徊边缘 提交于 2019-12-05 14:35:38

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.

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