Skip to content

Commit

Permalink
Distributed Tracing: Refactors Samples to use latest cosmosdb SDK (#4218
Browse files Browse the repository at this point in the history
)

* Updated Cosmosd SDK version in Open telemetry and AppInsight Samples

* clean up code

* fixd samples

* remove underscore from variable name
  • Loading branch information
sourabh1007 authored Dec 20, 2023
1 parent 7a32b96 commit 3cb1c55
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0-beta2" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.33.0-preview" />
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.37.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
Expand Down
55 changes: 38 additions & 17 deletions Microsoft.Azure.Cosmos.Samples/Usage/ApplicationInsights/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.WorkerService;
using Microsoft.Extensions.Logging.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;

internal class Program
{
private static readonly string databaseName = "samples";
private static readonly string containerName = "ai-sample";

private static TelemetryClient _telemetryClient;
private static TelemetryClient telemetryClient;

static async Task Main()
{
Expand Down Expand Up @@ -49,35 +48,57 @@ static async Task Main()
services.AddApplicationInsightsTelemetryWorkerService((ApplicationInsightsServiceOptions options) => options.ConnectionString = aiConnectionString);

IServiceProvider serviceProvider = services.BuildServiceProvider();
_telemetryClient = serviceProvider.GetRequiredService<TelemetryClient>();
telemetryClient = serviceProvider.GetRequiredService<TelemetryClient>();
// </SetUpApplicationInsights>

CosmosClientOptions options = new CosmosClientOptions()
{
IsDistributedTracingEnabled = true // Defaults to true, set to false to disable
};
using (CosmosClient client = new CosmosClient(endpoint, authKey, options))
{
Console.WriteLine($"Getting container reference for {containerName}.");
var infoOperation = telemetryClient.StartOperation<DependencyTelemetry>(".Net SDK : ApplicationInsights SDK"); // Application level activity to track the entire execution of the application

ContainerProperties properties = new ContainerProperties(containerName, partitionKeyPath: "/id");
var gops = telemetryClient.StartOperation<DependencyTelemetry>("GATEWAY MODE"); // Activity to track the execution of the gateway mode
await Program.RunCosmosDbOperation(ConnectionMode.Gateway, endpoint, authKey);
telemetryClient.StopOperation(gops);

await client.CreateDatabaseIfNotExistsAsync(databaseName);
Container container = await client.GetDatabase(databaseName).CreateContainerIfNotExistsAsync(properties);
var dops = telemetryClient.StartOperation<DependencyTelemetry>("DIRECT MODE"); // Activity to track the execution of the direct mode
await Program.RunCosmosDbOperation(ConnectionMode.Direct, endpoint, authKey);
telemetryClient.StopOperation(dops);

await Program.RunCrudDemo(container);
}
telemetryClient.StopOperation(infoOperation);
}
finally
{
// Explicitly calling Flush() followed by sleep is required for Application Insights logging in console apps to ensure that telemetry is sent to the back-end even if application terminates.
_telemetryClient?.Flush();
telemetryClient?.Flush();
await Task.Delay(5000);

Console.WriteLine("End of demo.");
}
}

private static async Task RunCosmosDbOperation(ConnectionMode connMode, string endpoint, string authKey)
{
// <EnableDistributedTracing>
CosmosClientOptions options = new CosmosClientOptions()
{
CosmosClientTelemetryOptions = new CosmosClientTelemetryOptions()
{
DisableDistributedTracing = false
},
ConnectionMode = connMode
};
// </EnableDistributedTracing>

using (CosmosClient client = new CosmosClient(endpoint, authKey, options))
{
Console.WriteLine($"Getting container reference for {containerName}.");

ContainerProperties properties = new ContainerProperties(containerName, partitionKeyPath: "/id");

await client.CreateDatabaseIfNotExistsAsync(databaseName);
Container container = await client.GetDatabase(databaseName).CreateContainerIfNotExistsAsync(properties);

await Program.RunCrudDemo(container);
}
}

public static async Task RunCrudDemo(Container container)
{
// Any operations will automatically generate telemetry
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Monitor.OpenTelemetry.Exporter" Version="1.0.0-beta.10" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.33.0-preview" />
<PackageReference Include="Microsoft.Extensions.Azure" Version="1.6.3" />
<PackageReference Include="Azure.Monitor.OpenTelemetry.Exporter" Version="1.1.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.37.0" />
<PackageReference Include="Microsoft.Extensions.Azure" Version="1.7.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.6.0-rc.1" />
</ItemGroup>

<ItemGroup>
Expand Down
71 changes: 48 additions & 23 deletions Microsoft.Azure.Cosmos.Samples/Usage/OpenTelemetry/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Azure.Monitor.OpenTelemetry.Exporter;
using System.Diagnostics;

internal class Program
{
Expand Down Expand Up @@ -52,15 +53,15 @@ static async Task Main()
serviceVersion: "1.0.0");

// Set up logging to forward logs to chosen exporter
using ILoggerFactory loggerFactory
using ILoggerFactory loggerFactory
= LoggerFactory.Create(builder => builder
.AddConfiguration(configuration.GetSection("Logging"))
.AddOpenTelemetry(options =>
{
options.IncludeFormattedMessage = true;
options.SetResourceBuilder(resource);
options.AddAzureMonitorLogExporter(o => o.ConnectionString = aiConnectionString); // Set up exporter of your choice
}));
{
options.IncludeFormattedMessage = true;
options.SetResourceBuilder(resource);
options.AddAzureMonitorLogExporter(o => o.ConnectionString = aiConnectionString); // Set up exporter of your choice
}));
/*.AddFilter(level => level == LogLevel.Error) // Filter is irrespective of event type or event name*/

AzureEventSourceLogForwarder logforwader = new AzureEventSourceLogForwarder(loggerFactory);
Expand All @@ -69,30 +70,28 @@ static async Task Main()
// Configure OpenTelemetry trace provider
AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", true);
_traceProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("Azure.Cosmos.Operation") // Cosmos DB source for operation level telemetry
.AddSource("Azure.Cosmos.Operation", // Cosmos DB source for operation level telemetry
"Azure.Cosmos.Request", // Cosmos DB source for DIRECT Mode network request level telemetry
"Sample.Application")
.AddAzureMonitorTraceExporter(o => o.ConnectionString = aiConnectionString) // Set up exporter of your choice
.AddHttpClientInstrumentation() // Added to capture HTTP telemetry
.SetResourceBuilder(resource)
.Build();
// </SetUpOpenTelemetry>

// <EnableDistributedTracing>
CosmosClientOptions options = new CosmosClientOptions()
ActivitySource source = new ActivitySource("Sample.Application");
using (_ = source.StartActivity(".Net SDK : Azure Monitor : Open Telemetry Sample")) // Application level activity to track the entire execution of the application
{
IsDistributedTracingEnabled = true // Defaults to true, set to false to disable
};

// </EnableDistributedTracing>
using (CosmosClient client = new CosmosClient(endpoint, authKey, options))
{
Console.WriteLine($"Getting container reference for {containerName}.");

ContainerProperties properties = new ContainerProperties(containerName, partitionKeyPath: "/id");

await client.CreateDatabaseIfNotExistsAsync(databaseName);
Container container = await client.GetDatabase(databaseName).CreateContainerIfNotExistsAsync(properties);

await Program.RunCrudDemo(container);
using (_ = source.StartActivity("GATEWAY MODE")) // Activity to track the execution of the gateway mode
{
await Program.RunCosmosDbOperation(ConnectionMode.Gateway, endpoint, authKey);
}
using (_ = source.StartActivity("DIRECT MODE")) // Activity to track the execution of the direct mode
{
await Program.RunCosmosDbOperation(ConnectionMode.Direct, endpoint, authKey);
}
}

}
finally
{
Expand All @@ -104,6 +103,32 @@ static async Task Main()
}
}

private static async Task RunCosmosDbOperation(ConnectionMode connMode, string endpoint, string authKey)
{
// <EnableDistributedTracing>
CosmosClientOptions options = new CosmosClientOptions()
{
CosmosClientTelemetryOptions = new CosmosClientTelemetryOptions()
{
DisableDistributedTracing = false
},
ConnectionMode = connMode
};
// </EnableDistributedTracing>

using (CosmosClient client = new CosmosClient(endpoint, authKey, options))
{
Console.WriteLine($"Getting container reference for {containerName}.");

ContainerProperties properties = new ContainerProperties(containerName, partitionKeyPath: "/id");

await client.CreateDatabaseIfNotExistsAsync(databaseName);
Container container = await client.GetDatabase(databaseName).CreateContainerIfNotExistsAsync(properties);

await Program.RunCrudDemo(container);
}
}

public static async Task RunCrudDemo(Container container)
{
// Any operations will automatically generate telemetry
Expand Down

0 comments on commit 3cb1c55

Please sign in to comment.