Trace
These samples are only valid for version 3. Please check the Samples directory for samples and documentation for version 4.0+
Debug messages for the MqttClient and MqttServer can be consumed using a static event. The following code shows how to manually write all trace messages to the console window.
// Write all trace messages to the console window.
MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
{
var trace = $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
if (e.TraceMessage.Exception != null)
{
trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
}
Console.WriteLine(trace);
};
For use cases where multiple clients are running in the same process and thus trace messages must be separated between the clients a custom logger must be specified via the constructor of the client and server.
The built in logger of this project allows specifying a log ID which must be set in the constructor of the logger. Doing this requires using a different constructor. The specified LogId can be accessed in the MqttNetLogMessage class for every generated log message.
The following code shows how to use a custom log ID.
// Use a custom log ID for the logger.
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient(new MqttNetLogger("MyCustomId"));
In cases where the trace must be forwarded to other trace libraries like SeriLog or Microsoft.Extensions.Logging etc. a custom logger must be implemented and also implementing the interface IMqttNetLogger. Then the new logger can be specified like in chapter "Extended Trace".