"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Enabling SignalR Tracing

by Tom FitzMacken

This document describes how to enable and configure tracing for SignalR servers and clients. Tracing enables you to view diagnostic information about events in your SignalR application.

This topic was originally written by Patrick Fletcher.

Software versions used in the tutorial

Questions and comments

Please leave feedback on how you liked this tutorial and what we could improve in the comments at the bottom of the page. If you have questions that are not directly related to the tutorial, you can post them to the ASP.NET SignalR forum or StackOverflow.com.

When tracing is enabled, a SignalR application creates log entries for events. You can log events from both the client and the server. Tracing on the server logs connection, scaleout provider, and message bus events. Tracing on the client logs connection events. In SignalR 2.1 and later, tracing on the client logs the full content of hub invocation messages.

Contents

## Enabling tracing on the server

You enable tracing on the server within the application’s configuration file (either App.config or Web.config depending on the type of project.) You specify which categories of events you want to log. In the configuration file, you also specify whether to log the events to a text file, the Windows event log, or a custom log using an implementation of TraceListener.

The server event categories include the following sorts of messages:

Source Messages
SignalR.SqlMessageBus SQL Message Bus scaleout provider setup, database operation, error, and timeout events
SignalR.ServiceBusMessageBus Service bus scaleout provider topic creation and subscription, error, and messaging events
SignalR.RedisMessageBus Redis scaleout provider connection, disconnection, and error events
SignalR.ScaleoutMessageBus Scaleout messaging events
SignalR.Transports.WebSocketTransport WebSocket transport connection, disconnection, messaging, and error events
SignalR.Transports.ServerSentEventsTransport ServerSentEvents transport connection, disconnection, messaging, and error events
SignalR.Transports.ForeverFrameTransport ForeverFrame transport connection, disconnection, messaging, and error events
SignalR.Transports.LongPollingTransport LongPolling transport connection, disconnection, messaging, and error events
SignalR.Transports.TransportHeartBeat Transport connection, disconnection, and keepalive events
SignalR.ReflectedHubDescriptorProvider Hub discovery events

### Logging server events to text files

The following code shows how to enable tracing for each category of event. This sample configures the application to log events to text files.

XML server code for enabling tracing

[!code-htmlMain]

   1:  <system.diagnostics>
   2:      <sources> 
   3:        <source name="SignalR.SqlMessageBus">
   4:          <listeners>
   5:            <add name="SignalR-Bus" />
   6:          </listeners>
   7:        </source>
   8:        <source name="SignalR.ServiceBusMessageBus">
   9:          <listeners>
  10:            <add name="SignalR-Bus" />
  11:          </listeners>
  12:        </source>
  13:        <source name="SignalR.RedisMessageBus">
  14:          <listeners>
  15:            <add name="SignalR-Bus" />
  16:          </listeners>
  17:        </source>
  18:        <source name="SignalR.ScaleoutMessageBus">
  19:          <listeners>
  20:            <add name="SignalR-Bus" />
  21:          </listeners>
  22:        </source>
  23:        <source name="SignalR.Transports.WebSocketTransport">
  24:          <listeners>
  25:            <add name="SignalR-Transports" />
  26:          </listeners>
  27:        </source>     
  28:        <source name="SignalR.Transports.ServerSentEventsTransport">
  29:          <listeners>
  30:            <add name="SignalR-Transports" />
  31:          </listeners>
  32:        </source>
  33:        <source name="SignalR.Transports.ForeverFrameTransport">
  34:          <listeners>
  35:            <add name="SignalR-Transports" />
  36:          </listeners>
  37:        </source>
  38:        <source name="SignalR.Transports.LongPollingTransport">
  39:          <listeners>
  40:            <add name="SignalR-Transports" />
  41:          </listeners>
  42:        </source>
  43:        <source name="SignalR.Transports.TransportHeartBeat">
  44:          <listeners>
  45:            <add name="SignalR-Transports" />
  46:          </listeners>
  47:        </source>
  48:        <source name="SignalR.ReflectedHubDescriptorProvider">
  49:          <listeners>
  50:            <add name="SignalR-Init" />
  51:          </listeners>
  52:        </source>
  53:      </sources>
  54:      <!-- Sets the trace verbosity level -->
  55:      <switches>
  56:        <add name="SignalRSwitch" value="Verbose" />
  57:      </switches>
  58:      <!-- Specifies the trace writer for output -->
  59:      <sharedListeners>
  60:        <!-- Listener for transport events -->
  61:        <add name="SignalR-Transports" type="System.Diagnostics.TextWriterTraceListener" initializeData="transports.log.txt" />
  62:        <!-- Listener for scaleout provider events -->
  63:        <add name="SignalR-Bus" type="System.Diagnostics.TextWriterTraceListener" initializeData="bus.log.txt" />
  64:        <!-- Listener for hub discovery events -->
  65:        <add name="SignalR-Init" type="System.Diagnostics.TextWriterTraceListener" initializeData="init.log.txt" />
  66:      </sharedListeners>
  67:      <trace autoflush="true" />
  68:    </system.diagnostics>

In the code above, the SignalRSwitch entry specifies the TraceLevel used for events sent to the specified log. In this case, it is set to Verbose which means all debugging and tracing messages are logged.

The following output shows entries from the transports.log.txt file for an application using the above configuration file. It shows a new connection, a removed connection, and transport heartbeat events.

[!code-consoleMain]

   1:  SignalR.Transports.TransportHeartBeat Information: 0 : Connection 9aa62c9b-09b3-416c-b367-06520e24f780 is New.
   2:  SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(9aa62c9b-09b3-416c-b367-06520e24f780)
   3:  SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(9aa62c9b-09b3-416c-b367-06520e24f780)
   4:  SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(9aa62c9b-09b3-416c-b367-06520e24f780)
   5:  SignalR.Transports.WebSocketTransport Information: 0 : CloseSocket(9aa62c9b-09b3-416c-b367-06520e24f780)
   6:  SignalR.Transports.WebSocketTransport Information: 0 : Abort(9aa62c9b-09b3-416c-b367-06520e24f780)
   7:  SignalR.Transports.TransportHeartBeat Information: 0 : Removing connection 9aa62c9b-09b3-416c-b367-06520e24f780
   8:  SignalR.Transports.WebSocketTransport Information: 0 : End(9aa62c9b-09b3-416c-b367-06520e24f780)
   9:  SignalR.Transports.WebSocketTransport Verbose: 0 : DrainWrites(9aa62c9b-09b3-416c-b367-06520e24f780)
  10:  SignalR.Transports.WebSocketTransport Information: 0 : CompleteRequest (9aa62c9b-09b3-416c-b367-06520e24f780)

### Logging server events to the event log

To log events to the event log rather than a text file, change the values for the entries in the sharedListeners node. The following code shows how to log server events to the event log:

XML server code for logging events to the event log

[!code-xmlMain]

   1:  <sharedListeners>
   2:    <!-- Listener for transport events -->
   3:    <add name="SignalR-Transports" type="System.Diagnostics.EventLogTraceListener" initializeData="SignalRScaleoutLog" />
   4:    <!-- Listener for scaleout provider events -->
   5:    <add name="SignalR-Bus" type="System.Diagnostics.EventLogTraceListener" initializeData="SignalRTransportLog" />
   6:    <!-- Listener for hub discovery events -->
   7:    <add name="SignalR-Init" type="System.Diagnostics.EventLogTraceListener" initializeData="SignalRInitLog" />
   8:  </sharedListeners>

The events are logged in the Application log, and are available through the Event Viewer, as shown below:

Event Viewer showing SignalR logs
Event Viewer showing SignalR logs

[!NOTE] When using the event log, set the TraceLevel to Error to keep the number of messages manageable.

## Enabling tracing in the .NET client (Windows Desktop apps)

The .NET client can log events to the console, a text file, or to a custom log using an implementation of TextWriter.

To enable logging in the .NET client, set the connection’s TraceLevel property to a TraceLevels value, and the TraceWriter property to a valid TextWriter instance.

### Logging Desktop client events to the console

The following C# code shows how to log events in the .NET client to the console:

[!code-csharpMain]

   1:  var hubConnection = new HubConnection("http://www.contoso.com/");
   2:  hubConnection.TraceLevel = TraceLevels.All;
   3:  hubConnection.TraceWriter = Console.Out;
   4:  IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");
   5:  stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));
   6:  await hubConnection.Start();

### Logging Desktop client events to a text file

The following C# code shows how to log events in the .NET client to a text file:

[!code-csharpMain]

   1:  var hubConnection = new HubConnection("http://www.contoso.com/");
   2:  var writer = new StreamWriter("ClientLog.txt");
   3:  writer.AutoFlush = true;
   4:  hubConnection.TraceLevel = TraceLevels.All;
   5:  hubConnection.TraceWriter = writer;
   6:  IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");
   7:  stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));
   8:  await hubConnection.Start();

The following output shows entries from the ClientLog.txt file for an application using the above configuration file. It shows the client connecting to the server, and the hub invoking a client method called addMessage:

[!code-consoleMain]

   1:  19:41:39.9103763 - null - ChangeState(Disconnected, Connecting)
   2:  19:41:40.3750726 - dd61fd48-d796-4518-b36b-ec1dcb970d72 - WS Connecting to: ws://localhost:8080/signalr/signalr/connect?transport=webSockets&clientProtocol=1.4&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAAh8Lp 
   3:  KH5%2FDkCQeR4ALAwR%2BAAAAAACAAAAAAADZgAAwAAAABAAAADHpCa7wm%2FbOhjluf%2Fm9GA9AAAAAASAAACgAAAAEA 
   4:  AAAEqRfJihLExRI6tZy7lWRwYoAAAApotSsJXW0OiwEgiUUi0pzhK6oKbz%2BkMeVbezuEDQLnJecM9otFe9PRQAAAAuHK
   5:  BlOnPmXt%2FhXV%2Felr1QvC156Q%3D%3D&connectionData=[{"Name":"MyHub"}]
   6:  19:41:40.4442923 - dd61fd48-d796-4518-b36b-ec1dcb970d72 - WS: OnMessage({"C":"d-5196BF5C-A,0|B,0|C,1|D,0","S":1,"M":[]})
   7:  19:41:40.4874324 - dd61fd48-d796-4518-b36b-ec1dcb970d72 - ChangeState(Connecting, Connected)
   8:  19:41:47.4511770 - dd61fd48-d796-4518-b36b-ec1dcb970d72 - WS: OnMessage({"C":"d-5196BF5C-A,1|B,0|C,1|D,0","M":[{"H":"MyHub","M":"addMessage","A":["User One","Hello!"]}]})
   9:  19:41:47.4576968 - dd61fd48-d796-4518-b36b-ec1dcb970d72 - WS: OnMessage({"I":"0"})
  10:  19:41:50.3959119 - dd61fd48-d796-4518-b36b-ec1dcb970d72 - WS: OnMessage({})
  11:  19:41:50.8928084 - dd61fd48-d796-4518-b36b-ec1dcb970d72 - WS: OnMessage({"C":"d-5196BF5C-A,2|B,0|C,1|D,0","M":[{"H":"MyHub","M":"addMessage","A":["User Two","Hello!"]}]})

## Enabling tracing in Windows Phone 8 clients

SignalR applications for Windows Phone apps use the same .NET client as desktop apps, but Console.Out and writing to a file with StreamWriter are not available. Instead, you need to create a custom implementation of TextWriter for tracing.

### Logging Windows Phone client events to the UI

The SignalR codebase includes a Windows Phone sample that writes trace output to a TextBlock using a custom TextWriter implementation called TextBlockWriter. This class can be found in the samples/Microsoft.AspNet.SignalR.Client.WP8.Samples project. When creating an instance of TextBlockWriter, pass in the current SynchronizationContext, and a StackPanel where it will create a TextBlock to use for trace output:

[!code-csharpMain]

   1:  Connection = new HubConnection(ServerURI);
   2:  var writer = new TextBlockWriter(SynchronizationContext.Current, StackPanelConsole);
   3:  Connection.TraceWriter = writer;
   4:  Connection.TraceLevel = TraceLevels.All;

The trace output will then be written to a new TextBlock created in the StackPanel you passed in:

### Logging Windows Phone client events to the debug console

To send output to the debug console rather than the UI, create an implementation of TextWriter that writes to the debug window, and assign it to your connection’s TraceWriter property:

[!code-csharpMain]

   1:  Connection = new HubConnection(ServerURI);
   2:  var writer = new DebugTextWriter();
   3:  Connection.TraceWriter = writer;
   4:  Connection.TraceLevel = TraceLevels.All;
   5:   
   6:  ...
   7:   
   8:  private class DebugTextWriter : TextWriter
   9:  {
  10:      private StringBuilder buffer;
  11:   
  12:      public DebugTextWriter()
  13:      {
  14:          buffer = new StringBuilder();
  15:      }
  16:   
  17:      public override void Write(char value)
  18:      {
  19:          switch (value)
  20:          {
  21:              case '\n':
  22:                  return;
  23:              case '\r':
  24:                  Debug.WriteLine(buffer.ToString());
  25:                  buffer.Clear();
  26:                  return;
  27:              default:
  28:                  buffer.Append(value);
  29:                  break;
  30:          }
  31:      }
  32:              
  33:      public override void Write(string value)
  34:      {
  35:          Debug.WriteLine(value);
  36:                  
  37:      }
  38:      #region implemented abstract members of TextWriter
  39:      public override Encoding Encoding
  40:      {
  41:          get { throw new NotImplementedException(); }
  42:      }
  43:      #endregion
  44:  }

Trace information will then be written to the debug window in Visual Studio:

## Enabling tracing in the JavaScript client

To enable client-side logging on a connection, set the logging property on the connection object before you call the start method to establish the connection.

Client JavaScript code for enabling tracing to the browser console (with the generated proxy)

[!code-javascriptMain]

   1:  $.connection.hub.logging = true;
   2:  $.connection.hub.start();

Client JavaScript code for enabling tracing to the browser console (without the generated proxy)

[!code-javascriptMain]

   1:  var connection = $.hubConnection();
   2:  connection.logging = true;
   3:  connection.start();

When tracing is enabled, the JavaScript client logs events to the browser console. To access the browser console, see Monitoring Transports.

The following screenshot shows a SignalR JavaScript client with tracing enabled. It shows connection and hub invocation events in the browser console:

SignalR tracing events in the browser console
SignalR tracing events in the browser console


Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/signalr/overview/testing-and-debugging/enabling-signalr-tracing.htm
< THANKS ME>