Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Internal] Samples: Adds OpenTelemetry and Application Insights samples #3818

Merged
3 commits merged into from
May 5, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"CosmosDBEndPointUrl": "https://localhost:8081",
"CosmosDBAuthorizationKey": "Super secret key",
"ApplicationInsightsConnectionString": "Super secret connection string"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
jcocchi marked this conversation as resolved.
Show resolved Hide resolved
<AssemblyName>Cosmos.Samples.ApplicationInsights</AssemblyName>
<RootNamespace>Cosmos.Samples.ApplicationInsights</RootNamespace>
<LangVersion>latest</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0-beta2" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.32.2-preview" />
<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" />
</ItemGroup>

<ItemGroup>
<None Include="appsettings.json" Link="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
120 changes: 120 additions & 0 deletions Microsoft.Azure.Cosmos.Samples/Usage/ApplicationInsights/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
namespace Cosmos.Samples.ApplicationInsights
{
using System;
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;

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

private static TelemetryClient? _telemetryClient;

static async Task Main()
{
try
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("AppSettings.json")
.Build();

string endpoint = configuration["CosmosDBEndPointUrl"];
if (string.IsNullOrEmpty(endpoint))
{
throw new ArgumentNullException("Please specify a valid CosmosDBEndPointUrl in the appSettings.json");
}

string authKey = configuration["CosmosDBAuthorizationKey"];
if (string.IsNullOrEmpty(authKey) || string.Equals(authKey, "Super secret key"))
{
throw new ArgumentException("Please specify a valid CosmosDBAuthorizationKey in the appSettings.json");
}

string aiConnectionString = configuration["ApplicationInsightsConnectionString"];
if (string.IsNullOrEmpty(authKey) || string.Equals(authKey, "Super secret connection string"))
{
throw new ArgumentException("Please specify a valid ApplicationInsightsConnectionString in the appSettings.json");
}

// <SetUpApplicationInsights>
IServiceCollection services = new ServiceCollection();
services.AddLogging(loggingBuilder => loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider>("Azure-Cosmos-Operation-Request-Diagnostics", LogLevel.Information));
jcocchi marked this conversation as resolved.
Show resolved Hide resolved
services.AddApplicationInsightsTelemetryWorkerService((ApplicationInsightsServiceOptions options) => options.ConnectionString = aiConnectionString);

IServiceProvider serviceProvider = services.BuildServiceProvider();
_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}.");

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

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

await Program.RunCrudDemo(container);
}
}
finally
{
// Explicitly calling Flush() followed by sleep is required for Application Insights logging in console apps.
// This is to ensure that even if application terminates, telemetry is sent to the back-end.
jcocchi marked this conversation as resolved.
Show resolved Hide resolved
_telemetryClient?.Flush();
await Task.Delay(5000);

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

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

for (int i = 1; i <= 5; i++)
{
await container.CreateItemAsync(new Item { Id = $"{i}", Status = "new" }, new PartitionKey($"{i}"));
Console.WriteLine($"Created document with id: {i}");
}

for (int i = 1; i <= 5; i++)
{
await container.ReadItemAsync<Item>($"{i}", new PartitionKey($"{i}"));
Console.WriteLine($"Read document with id: {i}");
}

for (int i = 1; i <= 5; i++)
{
await container.ReplaceItemAsync(new Item { Id = $"{i}", Status = "updated" }, $"{i}", new PartitionKey($"{i}"));
Console.WriteLine($"Updated document with id: {i}");
}

for (int i = 1; i <= 5; i++)
{
await container.DeleteItemAsync<Item>($"{i}", new PartitionKey($"{i}"));
Console.WriteLine($"Deleted document with id: {i}");
}
}
}

internal class Item
{
[JsonProperty("id")]
public string Id { get; set; }

public string Status { get; set; }
}
}
12 changes: 12 additions & 0 deletions Microsoft.Azure.Cosmos.Samples/Usage/Cosmos.Samples.Usage.sln
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CFPullModelAllVersionsAndDe
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CFPullModelLatestVersionMode", "CFPullModelLatestVersionMode\CFPullModelLatestVersionMode.csproj", "{985B0E0A-D480-4C3C-A1FC-589F2EC4BBF6}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTelemetry", "OpenTelemetry\OpenTelemetry.csproj", "{C6EF6948-C085-4013-A21F-99303ECBA7A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApplicationInsights", "ApplicationInsights\ApplicationInsights.csproj", "{55149A3C-A263-4EE5-AD2D-02FE9AC4D291}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -153,6 +157,14 @@ Global
{985B0E0A-D480-4C3C-A1FC-589F2EC4BBF6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{985B0E0A-D480-4C3C-A1FC-589F2EC4BBF6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{985B0E0A-D480-4C3C-A1FC-589F2EC4BBF6}.Release|Any CPU.Build.0 = Release|Any CPU
{C6EF6948-C085-4013-A21F-99303ECBA7A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C6EF6948-C085-4013-A21F-99303ECBA7A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C6EF6948-C085-4013-A21F-99303ECBA7A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C6EF6948-C085-4013-A21F-99303ECBA7A9}.Release|Any CPU.Build.0 = Release|Any CPU
{55149A3C-A263-4EE5-AD2D-02FE9AC4D291}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{55149A3C-A263-4EE5-AD2D-02FE9AC4D291}.Debug|Any CPU.Build.0 = Debug|Any CPU
{55149A3C-A263-4EE5-AD2D-02FE9AC4D291}.Release|Any CPU.ActiveCfg = Release|Any CPU
{55149A3C-A263-4EE5-AD2D-02FE9AC4D291}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Azure-Cosmos-Operation-Request-Diagnostics": "Information"
}
},
"CosmosDBEndPointUrl": "https://localhost:8081",
"CosmosDBAuthorizationKey": "Super secret key",
"ApplicationInsightsConnectionString": "Super secret connection string"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
jcocchi marked this conversation as resolved.
Show resolved Hide resolved
<AssemblyName>Cosmos.Samples.OpenTelemetry</AssemblyName>
<RootNamespace>Cosmos.Samples.OpenTelemetry</RootNamespace>
<LangVersion>latest</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Monitor.OpenTelemetry.Exporter" Version="1.0.0-beta.10" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.32.3-preview" />
jcocchi marked this conversation as resolved.
Show resolved Hide resolved
<PackageReference Include="Microsoft.Extensions.Azure" Version="1.6.3" />
<PackageReference Include="OpenTelemetry" Version="1.5.0-alpha.2" />
jcocchi marked this conversation as resolved.
Show resolved Hide resolved
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="7.0.2" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
</ItemGroup>

<ItemGroup>
<None Include="AppSettings.json" Link="AppSettings.json">
jcocchi marked this conversation as resolved.
Show resolved Hide resolved
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
138 changes: 138 additions & 0 deletions Microsoft.Azure.Cosmos.Samples/Usage/OpenTelemetry/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
namespace Cosmos.Samples.OpenTelemetry
{
using global::OpenTelemetry;
using global::OpenTelemetry.Trace;
using global::OpenTelemetry.Resources;
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.Azure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Azure.Monitor.OpenTelemetry.Exporter;

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

private static TracerProvider? _traceProvider;

static async Task Main()
{
try
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("AppSettings.json")
.Build();

string endpoint = configuration["CosmosDBEndPointUrl"];
if (string.IsNullOrEmpty(endpoint))
{
throw new ArgumentNullException("Please specify a valid CosmosDBEndPointUrl in the appSettings.json");
}

string authKey = configuration["CosmosDBAuthorizationKey"];
if (string.IsNullOrEmpty(authKey) || string.Equals(authKey, "Super secret key"))
{
throw new ArgumentException("Please specify a valid CosmosDBAuthorizationKey in the appSettings.json");
}

string aiConnectionString = configuration["ApplicationInsightsConnectionString"];
if (string.IsNullOrEmpty(authKey) || string.Equals(authKey, "Super secret connection string"))
{
throw new ArgumentException("Please specify a valid ApplicationInsightsConnectionString in the appSettings.json");
}

// <SetUpOpenTelemetery>
ResourceBuilder resource = ResourceBuilder.CreateDefault().AddService(
serviceName: serviceName,
serviceVersion: "1.0.0");

// Set up logging to forward logs to chosen exporter
using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddOpenTelemetry(options =>
{
options.IncludeScopes = true;
jcocchi marked this conversation as resolved.
Show resolved Hide resolved
options.IncludeFormattedMessage = true;
options.SetResourceBuilder(resource);
options.AddAzureMonitorLogExporter(o => o.ConnectionString = aiConnectionString); // Set up exporter of your choice
}));

AzureEventSourceLogForwarder logforwader = new AzureEventSourceLogForwarder(loggerFactory);
logforwader.Start();

// Configure OpenTelemetry trace provider
AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", true);
_traceProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("Azure.Cosmos.Operation") // Cosmos DB source for operation level telemetry
.AddAzureMonitorTraceExporter(o => o.ConnectionString = aiConnectionString) // Set up exporter of your choice
.SetResourceBuilder(resource)
.Build();
// <SetUpOpenTelemetery>

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}.");

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

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

await Program.RunCrudDemo(container);
}

}
finally
{
_traceProvider?.Dispose();
await Task.Delay(5000);

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

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

for(int i = 1; i <= 5; i++)
{
await container.CreateItemAsync(new Item { Id = $"{i}", Status = "new" }, new PartitionKey($"{i}"));
Console.WriteLine($"Created document with id: {i}");
}

for (int i = 1; i <= 5; i++)
{
await container.ReadItemAsync<Item>($"{i}", new PartitionKey($"{i}"));
Console.WriteLine($"Read document with id: {i}");
}

for (int i = 1; i <= 5; i++)
{
await container.ReplaceItemAsync(new Item { Id = $"{i}", Status = "updated" }, $"{i}", new PartitionKey($"{i}"));
Console.WriteLine($"Updated document with id: {i}");
}

for (int i = 1; i <= 5; i++)
{
await container.DeleteItemAsync<Item>($"{i}", new PartitionKey($"{i}"));
Console.WriteLine($"Deleted document with id: {i}");
}
}
}

internal class Item
{
[JsonProperty("id")]
public string Id { get; set; }

public string Status { get; set; }
}
}