Logging

To enable logging on the network level you write a LogingHandler and add it to your XmppClient.

Building a LoggingHandler

We build our LoggingHandler by deriving from XmppHandler class. Then we can tap into the Transport and Subscribe to:

DataReceived and DataSent

Those subscriptions expose the raw data which is received or sent over the Socket or WebSocket transports.

XmlReceived and XmlSent

These subscriptions give you access to the Xml which is received or sent over the Socket or WebSocket transports. Xml is a level above the raw data. Becuase to receive Xml raw data needs to be parsed with the Xml Tokenizer. And a Xml packet can be build from multiple data receive events. Also outgoinf Xml needs to get serialized and encoeded to UTF8 before it can be sent as a buffer over the network using a given transport.

using XmppDotNet;
using Serilog;
using System;
using System.Text;
using Serilog.Sinks.SystemConsole.Themes;

public class XmppLoggingHandler : XmppHandler
{
    public XmppLoggingHandler(XmppClient xmppClient) 
        : base(xmppClient)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console(theme: AnsiConsoleTheme.Code)
            .CreateLogger();

        //xmppClient.Transport.XmlReceived.Subscribe(
        //    xml => { Log.Information($"RECV: {xml}"); }
        //);

        //xmppClient.Transport.XmlSent.Subscribe(
        //    xml => { Log.Information($"SEND: {xml}"); }
        //);

        xmppClient.Transport.DataReceived.Subscribe(
            data => { Log.Information($"RECV: {Encoding.UTF8.GetString(data)}"); }
        );

        xmppClient.Transport.DataSent.Subscribe(
            data => { Log.Information($"SEND: {Encoding.UTF8.GetString(data)}"); }
        );
    }
}


var xmppClient = new XmppClient(pipelineInitializerAction)
{                
    Username = "username",
    Password = "secret",
    XmppDomain = "yourserver.com",
    
    // we disable compression and TLS only for debugging purposes here,
    // compressed and encrypted tcp socket data is not human readable
    Compression = false,    
    Tls = false
};     

Adding the logger to the XmppClient

using XmppDotNet;

var xmppClient = new XmppClient(
    conf =>
    {
        conf.UseSocketTransport();
        conf.AutoReconnect = true;
    },
    (handlers, client) => handlers.Add(new XmppLoggingHandler(client)))
{
    Jid = "user@server.com",
    Password = "secret"
};