Skip to content

Commit

Permalink
Refactor trace messages
Browse files Browse the repository at this point in the history
  • Loading branch information
chkr1011 committed Nov 21, 2017
1 parent 8411382 commit e0235ae
Show file tree
Hide file tree
Showing 18 changed files with 111 additions and 58 deletions.
10 changes: 2 additions & 8 deletions Build/MQTTnet.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,15 @@
<package >
<metadata>
<id>MQTTnet</id>
<version>2.5.2-rc1</version>
<version>2.5.2</version>
<authors>Christian Kratky</authors>
<owners>Christian Kratky</owners>
<licenseUrl>https://github.com/chkr1011/MQTTnet/blob/master/LICENSE</licenseUrl>
<projectUrl>https://github.com/chkr1011/MQTTnet</projectUrl>
<iconUrl>https://raw.githubusercontent.com/chkr1011/MQTTnet/master/Images/Logo_128x128.png</iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker).</description>
<releaseNotes>* [Core] Fixed library reference issues for .NET 4.6 and netstandard 2.0 (Thanks to @JanEggers).
* [Core] Several COM exceptions are now wrapped properly resulting in less warnings in the trace.
* [Core] Removed application message payload from trace to reduce trace size and increase performance.
* [Client] Fixed WebSocket sub protocol negotiation for ASP.NET Core 2 servers (Thanks to @JanEggers).
* [Client] Fixed broken connection after 30 seconds then using WebSocket protocol (Thanks to @ChristianRiedl).
* [Server] Client connections are now closed when the server is stopped (Thanks to @zhudanfei).
* [Server] Published messages from the server are now retained (if set) (Thanks to @ChristianRiedl). BREAKING CHANGE!
<releaseNotes>* [Core] Refactored trace messages.
</releaseNotes>
<copyright>Copyright Christian Kratky 2016-2017</copyright>
<tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags>
Expand Down
4 changes: 4 additions & 0 deletions MQTTnet.Core/Adapter/MqttChannelCommunicationAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,15 @@ public MqttChannelCommunicationAdapter(IMqttCommunicationChannel channel, IMqttP

public async Task ConnectAsync(TimeSpan timeout)
{
_logger.LogInformation("Connecting [Timeout={0}]", timeout);

await ExecuteAndWrapExceptionAsync(() => _channel.ConnectAsync().TimeoutAfter(timeout));
}

public async Task DisconnectAsync(TimeSpan timeout)
{
_logger.LogInformation("Disconnecting [Timeout={0}]", timeout);

await ExecuteAndWrapExceptionAsync(() => _channel.DisconnectAsync().TimeoutAfter(timeout));
}

Expand Down
2 changes: 1 addition & 1 deletion MQTTnet.Core/Packets/MqttConnAckPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public sealed class MqttConnAckPacket : MqttBasePacket

public override string ToString()
{
return nameof(MqttConnAckPacket) + ": [ConnectReturnCode=" + ConnectReturnCode + "] [IsSessionPresent=" + IsSessionPresent + "]";
return "ConnAck: [ConnectReturnCode=" + ConnectReturnCode + "] [IsSessionPresent=" + IsSessionPresent + "]";
}
}
}
2 changes: 1 addition & 1 deletion MQTTnet.Core/Packets/MqttConnectPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public sealed class MqttConnectPacket : MqttBasePacket

public override string ToString()
{
return nameof(MqttConnectPacket) + ": [ClientId=" + ClientId + "] [Username=" + Username + "] [Password=" + Password + "] [KeepAlivePeriod=" + KeepAlivePeriod + "] [CleanSession=" + CleanSession + "]";
return "Connect: [ClientId=" + ClientId + "] [Username=" + Username + "] [Password=" + Password + "] [KeepAlivePeriod=" + KeepAlivePeriod + "] [CleanSession=" + CleanSession + "]";
}
}
}
4 changes: 4 additions & 0 deletions MQTTnet.Core/Packets/MqttDisconnectPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@
{
public sealed class MqttDisconnectPacket : MqttBasePacket
{
public override string ToString()
{
return "Disconnect";
}
}
}
2 changes: 1 addition & 1 deletion MQTTnet.Core/Packets/MqttPingReqPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public sealed class MqttPingReqPacket : MqttBasePacket
{
public override string ToString()
{
return nameof(MqttPingReqPacket);
return "PingReq";
}
}
}
2 changes: 1 addition & 1 deletion MQTTnet.Core/Packets/MqttPingRespPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public sealed class MqttPingRespPacket : MqttBasePacket
{
public override string ToString()
{
return nameof(MqttPingRespPacket);
return "PingResp";
}
}
}
4 changes: 4 additions & 0 deletions MQTTnet.Core/Packets/MqttPubAckPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@
{
public sealed class MqttPubAckPacket : MqttBasePublishPacket
{
public override string ToString()
{
return "PubAck";
}
}
}
4 changes: 4 additions & 0 deletions MQTTnet.Core/Packets/MqttPubCompPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@
{
public sealed class MqttPubCompPacket : MqttBasePublishPacket
{
public override string ToString()
{
return "PubComp";
}
}
}
4 changes: 4 additions & 0 deletions MQTTnet.Core/Packets/MqttPubRecPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@
{
public sealed class MqttPubRecPacket : MqttBasePublishPacket
{
public override string ToString()
{
return "PubRec";
}
}
}
4 changes: 4 additions & 0 deletions MQTTnet.Core/Packets/MqttPubRelPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@
{
public sealed class MqttPubRelPacket : MqttBasePublishPacket
{
public override string ToString()
{
return "PubRel";
}
}
}
5 changes: 2 additions & 3 deletions MQTTnet.Core/Packets/MqttPublishPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ public sealed class MqttPublishPacket : MqttBasePublishPacket

public override string ToString()
{
return nameof(MqttPublishPacket) +
": [Topic=" + Topic + "]" +
" [PayloadLength=" + Payload?.Length + "]" +
return "Publish: [Topic=" + Topic + "]" +
" [Payload.Length=" + Payload?.Length + "]" +
" [QoSLevel=" + QualityOfServiceLevel + "]" +
" [Dup=" + Dup + "]" +
" [Retain=" + Retain + "]" +
Expand Down
2 changes: 1 addition & 1 deletion MQTTnet.Core/Packets/MqttSubAckPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public sealed class MqttSubAckPacket : MqttBasePacket, IMqttPacketWithIdentifier
public override string ToString()
{
var subscribeReturnCodesText = string.Join(",", SubscribeReturnCodes.Select(f => f.ToString()));
return nameof(MqttSubAckPacket) + ": [PacketIdentifier=" + PacketIdentifier + "] [SubscribeReturnCodes=" + subscribeReturnCodesText + "]";
return "SubAck: [PacketIdentifier=" + PacketIdentifier + "] [SubscribeReturnCodes=" + subscribeReturnCodesText + "]";
}
}
}
2 changes: 1 addition & 1 deletion MQTTnet.Core/Packets/MqttSubscribePacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public sealed class MqttSubscribePacket : MqttBasePacket, IMqttPacketWithIdentif
public override string ToString()
{
var topicFiltersText = string.Join(",", TopicFilters.Select(f => f.Topic + "@" + f.QualityOfServiceLevel));
return nameof(MqttSubscribePacket) + ": [PacketIdentifier=" + PacketIdentifier + "] [TopicFilters=" + topicFiltersText + "]";
return "Subscribe: [PacketIdentifier=" + PacketIdentifier + "] [TopicFilters=" + topicFiltersText + "]";
}
}
}
5 changes: 5 additions & 0 deletions MQTTnet.Core/Packets/MqttUnsubAckPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,10 @@
public sealed class MqttUnsubAckPacket : MqttBasePacket, IMqttPacketWithIdentifier
{
public ushort PacketIdentifier { get; set; }

public override string ToString()
{
return "UnsubAck: [PacketIdentifier=" + PacketIdentifier + "]";
}
}
}
6 changes: 6 additions & 0 deletions MQTTnet.Core/Packets/MqttUnsubscribe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,11 @@ public sealed class MqttUnsubscribePacket : MqttBasePacket, IMqttPacketWithIdent
public ushort PacketIdentifier { get; set; }

public IList<string> TopicFilters { get; set; } = new List<string>();

public override string ToString()
{
var topicFiltersText = string.Join(",", TopicFilters);
return "Subscribe: [PacketIdentifier=" + PacketIdentifier + "] [TopicFilters=" + topicFiltersText + "]";
}
}
}
77 changes: 41 additions & 36 deletions MQTTnet.Core/Server/MqttClientRetainedMessagesManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,42 +57,7 @@ public async Task HandleMessageAsync(string clientId, MqttApplicationMessage app
await _gate.WaitAsync().ConfigureAwait(false);
try
{
var saveIsRequired = false;

if (applicationMessage.Payload?.Any() == false)
{
saveIsRequired = _retainedMessages.Remove(applicationMessage.Topic);
_logger.LogInformation("Client '{0}' cleared retained message for topic '{1}'.", clientId, applicationMessage.Topic);
}
else
{
if (!_retainedMessages.ContainsKey(applicationMessage.Topic))
{
_retainedMessages[applicationMessage.Topic] = applicationMessage;
saveIsRequired = true;
}
else
{
var existingMessage = _retainedMessages[applicationMessage.Topic];
if (existingMessage.QualityOfServiceLevel != applicationMessage.QualityOfServiceLevel || !existingMessage.Payload.SequenceEqual(applicationMessage.Payload ?? new byte[0]))
{
_retainedMessages[applicationMessage.Topic] = applicationMessage;
saveIsRequired = true;
}
}

_logger.LogInformation("Client '{0}' set retained message for topic '{1}'.", clientId, applicationMessage.Topic);
}

if (!saveIsRequired)
{
_logger.LogTrace("Skipped saving retained messages because no changes were detected.");
}

if (saveIsRequired && _options.Storage != null)
{
await _options.Storage.SaveRetainedMessagesAsync(_retainedMessages.Values.ToList());
}
await HandleMessageInternalAsync(clientId, applicationMessage);
}
catch (Exception exception)
{
Expand Down Expand Up @@ -137,5 +102,45 @@ public async Task<List<MqttApplicationMessage>> GetSubscribedMessagesAsync(MqttS

return retainedMessages;
}

private async Task HandleMessageInternalAsync(string clientId, MqttApplicationMessage applicationMessage)
{
var saveIsRequired = false;

if (applicationMessage.Payload?.Any() == false)
{
saveIsRequired = _retainedMessages.Remove(applicationMessage.Topic);
_logger.LogInformation("Client '{0}' cleared retained message for topic '{1}'.", clientId, applicationMessage.Topic);
}
else
{
if (!_retainedMessages.ContainsKey(applicationMessage.Topic))
{
_retainedMessages[applicationMessage.Topic] = applicationMessage;
saveIsRequired = true;
}
else
{
var existingMessage = _retainedMessages[applicationMessage.Topic];
if (existingMessage.QualityOfServiceLevel != applicationMessage.QualityOfServiceLevel || !existingMessage.Payload.SequenceEqual(applicationMessage.Payload ?? new byte[0]))
{
_retainedMessages[applicationMessage.Topic] = applicationMessage;
saveIsRequired = true;
}
}

_logger.LogInformation("Client '{0}' set retained message for topic '{1}'.", clientId, applicationMessage.Topic);
}

if (!saveIsRequired)
{
_logger.LogTrace("Skipped saving retained messages because no changes were detected.");
}

if (saveIsRequired && _options.Storage != null)
{
await _options.Storage.SaveRetainedMessagesAsync(_retainedMessages.Values.ToList());
}
}
}
}
30 changes: 25 additions & 5 deletions Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Cryptography.Certificates;
Expand All @@ -18,6 +19,8 @@ namespace MQTTnet.TestApp.UniversalWindows
{
public sealed partial class MainPage
{
private readonly ConcurrentQueue<MqttNetTraceMessage> _traceMessages = new ConcurrentQueue<MqttNetTraceMessage>();

private IMqttClient _mqttClient;
private IMqttServer _mqttServer;

Expand All @@ -30,15 +33,32 @@ public MainPage()

private async void OnTraceMessagePublished(object sender, MqttNetTraceMessagePublishedEventArgs e)
{
var text = $"[{e.TraceMessage.Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{e.TraceMessage.Level}] [{e.TraceMessage.Source}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Message}]{Environment.NewLine}";
if (e.TraceMessage.Exception != null)
_traceMessages.Enqueue(e.TraceMessage);
while (_traceMessages.Count > 100)
{
_traceMessages.TryDequeue(out _);
}

var logText = new StringBuilder();
foreach (var traceMessage in _traceMessages)
{
text += $"{e.TraceMessage.Exception}{Environment.NewLine}";
logText.AppendFormat(
"[{0:yyyy-MM-dd HH:mm:ss.fff}] [{1}] [{2}] [{3}] [{4}]{5}", traceMessage.Timestamp,
traceMessage.Level,
traceMessage.Source,
traceMessage.ThreadId,
traceMessage.Message,
Environment.NewLine);

if (traceMessage.Exception != null)
{
logText.AppendLine(traceMessage.Exception.ToString());
}
}

await Trace.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
Trace.Text += text;
Trace.Text = logText.ToString();
});
}

Expand Down

0 comments on commit e0235ae

Please sign in to comment.