Trace Azure IoT device-to-cloud messages with distributed tracing (preview)
Microsoft Azure IoT Hub currently supports distributed tracing as a preview feature.
IoT Hub is one of the first Azure services to support distributed tracing. As more Azure services support distributed tracing, you'll be able trace IoT messages throughout the Azure services involved in your solution. For a background on distributed tracing, see Distributed Tracing.
Enabling distributed tracing for IoT Hub gives you the ability to:
- Precisely monitor the flow of each message through IoT Hub using trace context. This trace context includes correlation IDs that allow you to correlate events from one component with events from another component. It can be applied for a subset or all IoT device messages using device twin.
- Automatically log the trace context to Azure Monitor Logs.
- Measure and understand message flow and latency from devices to IoT Hub and routing endpoints.
- Start considering how you want to implement distributed tracing for the non-Azure services in your IoT solution.
In this article, you use the Azure IoT device SDK for C with distributed tracing. Distributed tracing support is still in progress for the other SDKs.
Prerequisites
The preview of distributed tracing is currently only supported for IoT Hubs created in the following regions:
- North Europe
- Southeast Asia
- West US 2
This article assumes that you're familiar with sending telemetry messages to your IoT hub. Make sure you've completed the Send telemetry C Quickstart.
Register a device with your IoT hub (steps available in each Quickstart) and note down the connection string.
Install the latest version of Git.
Configure IoT Hub
In this section, you configure an IoT Hub to log distributed tracing attributes (correlation IDs and timestamps).
Navigate to your IoT hub in the Azure portal.
In the left pane for your IoT hub, scroll down to the Monitoring section and click Diagnostics settings.
Click Add diagnostic setting.
In the Name field, enter a name for a new diagnostic setting. For example, DistributedTracingSettings.
Choose one or more of the following options that determine where the logging will be sent:
- Archive to a storage account: Configure a storage account to contain the logging information.
- Stream to an event hub: Configure an event hub to contain the logging information.
- Send to Log Analytics: Configure a log analytics workspace to contain the logging information.
In the Log section, select the operations that you want logging information for.
Make sure to include DistributedTracing, and configure a Retention for how many days you want the logging retained. Log retention does affect storage costs.

Click Save for the new setting.
(Optional) To see the messages flow to different places, set up routing rules to at least two different endpoints.
Once the logging is turned on, IoT Hub records a log when a message containing valid trace properties is encountered in any of the following situations:
- The message arrives at IoT Hub's gateway.
- The message is processed by the IoT Hub.
- The message is routed to custom endpoints. Routing must be enabled.
To learn more about these logs and their schemas, see Monitor IoT Hub and Distributed tracing in IoT Hub resource logs.
Set up device
In this section, you prepare a development environment for use with the Azure IoT C SDK. Then, you modify one of samples to enable distributed tracing on your device's telemetry messages.
These instructions are for building the sample on Windows. For other environments, see Compile the C SDK or Prepackaged C SDK for Platform Specific Development.
Clone the source code and initialize
Install "Desktop development with C++" workload for Visual Studio 2019. Visual Studio 2017 is also supported.
Install CMake. Make sure it is in your
PATHby typingcmake -versionfrom a command prompt.Open a command prompt or Git Bash shell. Run the following commands to clone the latest release of the Azure IoT C SDK GitHub repository:
git clone -b public-preview https://github.com/Azure/azure-iot-sdk-c.git cd azure-iot-sdk-c git submodule update --initYou should expect this operation to take several minutes to complete.
Create a
cmakesubdirectory in the root directory of the git repository, and navigate to that folder. Run the following commands from theazure-iot-sdk-cdirectory:mkdir cmake cd cmake cmake ..If
cmakecan't find your C++ compiler, you might get build errors while running the above command. If that happens, try running this command in the Visual Studio command prompt.Once the build succeeds, the last few output lines will look similar to the following output:
$ cmake .. -- Building for: Visual Studio 15 2017 -- Selecting Windows SDK version 10.0.16299.0 to target Windows 10.0.17134. -- The C compiler identification is MSVC 19.12.25835.0 -- The CXX compiler identification is MSVC 19.12.25835.0 ... -- Configuring done -- Generating done -- Build files have been written to: E:/IoT Testing/azure-iot-sdk-c/cmake
Edit the send telemetry sample to enable distributed tracing
Use an editor to open the
azure-iot-sdk-c/iothub_client/samples/iothub_ll_telemetry_sample/iothub_ll_telemetry_sample.csource file.Find the declaration of the
connectionStringconstant:/* Paste in the your iothub connection string */ static const char* connectionString = "[device connection string]"; #define MESSAGE_COUNT 5000 static bool g_continueRunning = true; static size_t g_message_count_send_confirmations = 0;Replace the value of the
connectionStringconstant with the device connection string you made a note of in the register a device section of the Send telemetry C Quickstart.Change the
MESSAGE_COUNTdefine to5000:/* Paste in the your iothub connection string */ static const char* connectionString = "[device connection string]"; #define MESSAGE_COUNT 5000 static bool g_continueRunning = true; static size_t g_message_count_send_confirmations = 0;Find the line of code that calls
IoTHubDeviceClient_LL_SetConnectionStatusCallbackto register a connection status callback function before the send message loop. Add code under that line as shown below to callIoTHubDeviceClient_LL_EnablePolicyConfigurationenabling distributed tracing for the device:// Setting connection status callback to get indication of connection to iothub (void)IoTHubDeviceClient_LL_SetConnectionStatusCallback(device_ll_handle, connection_status_callback, NULL); // Enabled the distrubted tracing policy for the device (void)IoTHubDeviceClient_LL_EnablePolicyConfiguration(device_ll_handle, POLICY_CONFIGURATION_DISTRIBUTED_TRACING, true); do { if (messages_sent < MESSAGE_COUNT)The
IoTHubDeviceClient_LL_EnablePolicyConfigurationfunction enables policies for specific IoTHub features that are configured via device twins. OncePOLICY_CONFIGURATION_DISTRIBUTED_TRACINGis enabled with the line of code above, the tracing behavior of the device will reflect distributed tracing changes made on the device twin.To keep the sample app running without using up all your quota, add a one-second delay at the end of the send message loop:
else if (g_message_count_send_confirmations >= MESSAGE_COUNT) { // After all messages are all received stop running g_continueRunning = false; } IoTHubDeviceClient_LL_DoWork(device_ll_handle); ThreadAPI_Sleep(1000); } while (g_continueRunning);
Compile and run
Navigate to the iothub_ll_telemetry_sample project directory from the CMake directory (
azure-iot-sdk-c/cmake) you created earlier, and compile the sample:cd iothub_client/samples/iothub_ll_telemetry_sample cmake --build . --target iothub_ll_telemetry_sample --config DebugRun the application. The device sends telemetry supporting distributed tracing.
Debug/iothub_ll_telemetry_sample.exeKeep the app running. Optionally observe the message being sent to IoT Hub by looking at the console window.
Workaround for third-party clients
It's not trivial to preview the distributed tracing feature without using the C SDK. Thus, this approach is not recommended.
First, you must implement all the IoT Hub protocol primitives in your messages by following the dev guide Create and read IoT Hub messages. Then, edit the protocol properties in the MQTT/AMQP messages to add tracestate as system property. Specifically,
- For MQTT, add
%24.tracestate=timestamp%3d1539243209to the message topic, where1539243209should be replaced with the creation time of the message in the unix timestamp format. As an example, refer to the implementation in the C SDK - For AMQP, add
key("tracestate")andvalue("timestamp=1539243209")as message annotation. For a reference implementation, see here.
To control the percentage of messages containing this property, implement logic to listen to cloud-initiated events such as twin updates.
Update sampling options
To change the percentage of messages to be traced from the cloud, you must update the device twin. You can accomplish this in multiple ways including the JSON editor in portal and the IoT Hub service SDK. The following subsections provide examples.
Update using the portal
Navigate to your IoT hub in Azure portal, then click IoT devices.
Click your device.
Look for Enable distributed tracing (preview), then select Enable.

Choose a Sampling rate between 0% and 100%.
Click Save.
Wait a few seconds, and hit Refresh, then if successfully acknowledged by device, a sync icon with a checkmark appears.
Go back to the console window for the telemetry message app. You will see messages being sent with
tracestatein the application properties.
(Optional) Change the sampling rate to a different value, and observe the change in frequency that messages include
tracestatein the application properties.
Update using Azure IoT Hub for VS Code
Install VS Code, then install the latest version of Azure IoT Hub for VS Code from here.
Open VS Code and set up IoT Hub connection string.
Expand the device and look for Distributed Tracing Setting (Preview). Under it, click Update Distributed Tracing Setting (Preview) of sub node.

In the popup window, select Enable, then press Enter to confirm 100 as sampling rate.


Bulk update for multiple devices
To update the distributed tracing sampling configuration for multiple devices, use automatic device configuration. Make sure you follow this twin schema:
{
"properties": {
"desired": {
"azureiot*com^dtracing^1": {
"sampling_mode": 1,
"sampling_rate": 100
}
}
}
}
| Element name | Required | Type | Description |
|---|---|---|---|
sampling_mode |
Yes | Integer | Two mode values are currently supported to turn sampling on and off. 1 is On and, 2 is Off. |
sampling_rate |
Yes | Integer | This value is a percentage. Only values from 0 to 100 (inclusive) are permitted. |
Query and visualize
To see all the traces logged by an IoT Hub, query the log store that you selected in diagnostic settings. This section walks through a couple different options.
Query using Log Analytics
If you've set up Log Analytics with resource logs, query by looking for logs in the DistributedTracing category. For example, this query shows all the traces logged:
// All distributed traces
AzureDiagnostics
| where Category == "DistributedTracing"
| project TimeGenerated, Category, OperationName, Level, CorrelationId, DurationMs, properties_s
| order by TimeGenerated asc
Example logs as shown by Log Analytics:
| TimeGenerated | OperationName | Category | Level | CorrelationId | DurationMs | Properties |
|---|---|---|---|---|---|---|
| 2018-02-22T03:28:28.633Z | DiagnosticIoTHubD2C | DistributedTracing | Informational | 00-8cd869a412459a25f5b4f31311223344-0144d2590aacd909-01 | {"deviceId":"AZ3166","messageSize":"96","callerLocalTimeUtc":"2018-02-22T03:27:28.633Z","calleeLocalTimeUtc":"2018-02-22T03:27:28.687Z"} | |
| 2018-02-22T03:28:38.633Z | DiagnosticIoTHubIngress | DistributedTracing | Informational | 00-8cd869a412459a25f5b4f31311223344-349810a9bbd28730-01 | 20 | {"isRoutingEnabled":"false","parentSpanId":"0144d2590aacd909"} |
| 2018-02-22T03:28:48.633Z | DiagnosticIoTHubEgress | DistributedTracing | Informational | 00-8cd869a412459a25f5b4f31311223344-349810a9bbd28730-01 | 23 | {"endpointType":"EventHub","endpointName":"myEventHub", "parentSpanId":"0144d2590aacd909"} |
To understand the different types of logs, see Azure IoT Hub distributed tracing logs.
Understand Azure IoT distributed tracing
Context
Many IoT solutions, including our own reference architecture (English only), generally follow a variant of the microservice architecture. As an IoT solution grows more complex, you end up using a dozen or more microservices. These microservices may or may not be from Azure. Pinpointing where IoT messages are dropping or slowing down can become challenging. For example, you have an IoT solution that uses 5 different Azure services and 1500 active devices. Each device sends 10 device-to-cloud messages/second (for a total of 15,000 messages/second), but you notice that your web app sees only 10,000 messages/second. Where is the issue? How do you find the culprit?
Distributed tracing pattern in microservice architecture
To reconstruct the flow of an IoT message across different services, each service should propagate a correlation ID that uniquely identifies the message. Once collected in a centralized system, correlation IDs enable you to see message flow. This method is called the distributed tracing pattern.
To support wider adoption for distributed tracing, Microsoft is contributing to W3C standard proposal for distributed tracing.
IoT Hub support
Once enabled, distributed tracing support for IoT Hub will follow this flow:
- A message is generated on the IoT device.
- The IoT device decides (with help from cloud) that this message should be assigned with a trace context.
- The SDK adds a
tracestateto the message property, containing the message creation timestamp. - The IoT device sends the message to IoT Hub.
- The message arrives at IoT hub gateway.
- IoT Hub looks for the
tracestatein the message properties, and checks to see if it's in the correct format. - If so, IoT Hub generates a globally unique
trace-idfor the message, aspan-idfor the "hop", and logs them to IoT Hub distributed tracing logs under the operationDiagnosticIoTHubD2C. - Once the message processing is finished, IoT Hub generates another
span-idand logs it along with the existingtrace-idunder the operationDiagnosticIoTHubIngress. - If routing is enabled for the message, IoT Hub writes it to the custom endpoint, and logs another
span-idwith the sametrace-idunder the categoryDiagnosticIoTHubEgress. - The steps above are repeated for each message generated.
Public preview limits and considerations
- Proposal for W3C Trace Context standard is currently a working draft.
- Currently, the only development language supported by client SDK is C.
- Cloud-to-device twin capability isn't available for IoT Hub basic tier. However, IoT Hub will still log to Azure Monitor if it sees a properly composed trace context header.
- To ensure efficient operation, IoT Hub will impose a throttle on the rate of logging that can occur as part of distributed tracing.
Next steps
- To learn more about the general distributed tracing pattern in microservices, see Microservice architecture pattern: distributed tracing.
- To set up configuration to apply distributed tracing settings to a large number of devices, see Configure and monitor IoT devices at scale.
- To learn more about Azure Monitor, see What is Azure Monitor?.
- To learn more about using Azure Monitor with IoT Hub, see Monitor IoT Hub