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

[AzureMonitorOpenTelemetryDistro] AddAzureMonitorOpenTelemetry extension methods and AzureMonitorOpenTelemetryOptions #34198

Merged
merged 13 commits into from
Feb 24, 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
2 changes: 2 additions & 0 deletions eng/Packages.Data.props
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@

<!-- OpenTelemetry dependency approved for Azure.Monitor.OpenTelemetry.Exporter package only -->
<PackageReference Update="OpenTelemetry" Version="[1.4.0-rc.4]" Condition="'$(MSBuildProjectName)' == 'Azure.Monitor.OpenTelemetry.Exporter'" />
<PackageReference Update="OpenTelemetry.Extensions.Hosting" Version="1.4.0-rc.4" />
<PackageReference Update="OpenTelemetry.Instrumentation.AspNetCore" Version="1.0.0-rc9.13" />
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved
<PackageReference Update="OpenTelemetry.Extensions.PersistentStorage" Version="1.0.0-beta.1" Condition="'$(MSBuildProjectName)' == 'Azure.Monitor.OpenTelemetry.Exporter'" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Dependent Projects", "Depen
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Monitor.OpenTelemetry.Exporter", "..\Azure.Monitor.OpenTelemetry.Exporter\src\Azure.Monitor.OpenTelemetry.Exporter.csproj", "{4158B8A7-971D-4A57-B4C8-5077BFD10AE6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples.AspNetCore", "tests\Examples.AspNetCore\Examples.AspNetCore.csproj", "{6F094CAA-F6BB-4A9C-9D1F-1165F0758C99}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -30,6 +32,10 @@ Global
{4158B8A7-971D-4A57-B4C8-5077BFD10AE6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4158B8A7-971D-4A57-B4C8-5077BFD10AE6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4158B8A7-971D-4A57-B4C8-5077BFD10AE6}.Release|Any CPU.Build.0 = Release|Any CPU
{6F094CAA-F6BB-4A9C-9D1F-1165F0758C99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6F094CAA-F6BB-4A9C-9D1F-1165F0758C99}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6F094CAA-F6BB-4A9C-9D1F-1165F0758C99}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6F094CAA-F6BB-4A9C-9D1F-1165F0758C99}.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,30 @@
namespace Azure.Monitor.OpenTelemetry
{
public static partial class AzureMonitorOpenTelemetryExtensions
{
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddAzureMonitorOpenTelemetry(this Microsoft.Extensions.DependencyInjection.IServiceCollection services, Azure.Monitor.OpenTelemetry.AzureMonitorOpenTelemetryOptions? options = null) { throw null; }
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddAzureMonitorOpenTelemetry(this Microsoft.Extensions.DependencyInjection.IServiceCollection services, Microsoft.Extensions.Configuration.IConfiguration configuration) { throw null; }
}
public partial class AzureMonitorOpenTelemetryOptions
{
public AzureMonitorOpenTelemetryOptions() { }
public string ConnectionString { get { throw null; } set { } }
public bool DisableLogs { get { throw null; } set { } }
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved
public bool DisableMetrics { get { throw null; } set { } }
public bool DisableOfflineStorage { get { throw null; } set { } }
public bool DisableTraces { get { throw null; } set { } }
public Azure.Monitor.OpenTelemetry.Metrics Metrics { get { throw null; } set { } }
public string StorageDirectory { get { throw null; } set { } }
public Azure.Monitor.OpenTelemetry.Traces Traces { get { throw null; } set { } }
}
public partial class Metrics
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved
{
public Metrics() { }
public bool DisableAspNetInstrumentation { get { throw null; } set { } }
}
public partial class Traces
{
public Traces() { }
public bool DisableAspNetInstrumentation { get { throw null; } set { } }
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
<IncludeOperationsSharedSource>true</IncludeOperationsSharedSource>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="OpenTelemetry.Extensions.Hosting" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Azure.Monitor.OpenTelemetry.Exporter\src\Azure.Monitor.OpenTelemetry.Exporter.csproj" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using Azure.Monitor.OpenTelemetry.Exporter;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

namespace Azure.Monitor.OpenTelemetry
{
/// <summary>
/// Extension methods for setting up Azure Monitor OpenTelemetry in an <see cref="IServiceCollection" />.
/// </summary>
public static class AzureMonitorOpenTelemetryExtensions
{
/// <summary>
/// Adds Azure Monitor OpenTelemetry into service collection.
/// </summary>
/// <param name="services"><see cref="IServiceCollection"/>.</param>
/// <param name="configuration"><see cref="IConfiguration"/>.</param>
/// <returns><see cref="IServiceCollection"/></returns>
public static IServiceCollection AddAzureMonitorOpenTelemetry(this IServiceCollection services, IConfiguration configuration)
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved
{
var options = new AzureMonitorOpenTelemetryOptions();
configuration.Bind(options);
return services.AddAzureMonitorOpenTelemetry(options);
}

/// <summary>
/// Adds Azure Monitor OpenTelemetry into service collection.
/// </summary>
/// <param name="services"><see cref="IServiceCollection"/>.</param>
/// <param name="options">The <see cref="AzureMonitorOpenTelemetryOptions" /> instance for configuration.</param>
/// <returns><see cref="IServiceCollection"/></returns>
public static IServiceCollection AddAzureMonitorOpenTelemetry(this IServiceCollection services, AzureMonitorOpenTelemetryOptions? options = null)
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved
{
options ??= new AzureMonitorOpenTelemetryOptions();
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved

var builder = services.AddOpenTelemetry();

if (!options.DisableTraces)
{
builder.WithTracing(b => b
.ValidateAndAddInstrumentation((i) => i.AddAspNetCoreInstrumentation(), options.Traces.DisableAspNetInstrumentation)
.AddAzureMonitorTraceExporter(o =>
{
o.ConnectionString = options.ConnectionString;
o.DisableOfflineStorage = options.DisableOfflineStorage;
o.StorageDirectory = options.StorageDirectory;
}));
}

if (!options.DisableMetrics)
{
builder.WithMetrics(b => b
.ValidateAndAddInstrumentation((i) => i.AddAspNetCoreInstrumentation(), options.Metrics.DisableAspNetInstrumentation)
.AddAzureMonitorMetricExporter(o =>
{
o.ConnectionString = options.ConnectionString;
o.DisableOfflineStorage = options.DisableOfflineStorage;
o.StorageDirectory = options.StorageDirectory;
}));
}

return services;
}

private static T ValidateAndAddInstrumentation<T>(this T builder, Action<T> configure, bool isDisabled)
{
if (!isDisabled)
{
configure(builder);
}

return builder;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable disable
TimothyMothra marked this conversation as resolved.
Show resolved Hide resolved
#pragma warning disable SA1402 // File may only contain a single type
#pragma warning disable AZC0012 // Avoid single word type names
#pragma warning disable CA1724 // Conflict Metrics name with OpenTelemetry.Metrics

namespace Azure.Monitor.OpenTelemetry
{
/// <summary>
/// Options that allow users to configure the Azure Monitor OpenTelemetry.
/// </summary>
public class AzureMonitorOpenTelemetryOptions
{
/// <summary>
/// The Connection String provides users with a single configuration setting to identify the Azure Monitor resource and endpoint.
/// </summary>
/// <remarks>
/// (https://docs.microsoft.com/azure/azure-monitor/app/sdk-connection-string).
/// </remarks>
public string ConnectionString { get; set; } = "InstrumentationKey=00000000-0000-0000-0000-000000000000";

/// <summary>
/// Gets or sets a value indicating whether Traces should be enabled.
/// </summary>
public bool DisableTraces { get; set; }

/// <summary>
/// Gets or sets a value indicating whether Metrics should be enabled.
/// </summary>
public bool DisableMetrics { get; set; }

/// <summary>
/// Gets or sets a value indicating whether Logs should be enabled.
/// </summary>
public bool DisableLogs { get; set; }

/// <summary>
/// Override the default directory for offline storage.
/// </summary>
public string StorageDirectory { get; set; }

/// <summary>
/// Disable offline storage.
/// </summary>
public bool DisableOfflineStorage { get; set; }

/// <summary>
/// Traces Configuration.
/// </summary>
public Traces Traces { get; set; } = new Traces();

/// <summary>
/// Metrics Configuration.
/// </summary>
public Metrics Metrics { get; set; } = new Metrics();
}

/// <summary>
/// Traces Configuration.
/// </summary>
public class Traces
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved
{
/// <summary>
/// Gets or sets a value indicating whether AspNet Instrumentation should be enabled.
/// </summary>
public bool DisableAspNetInstrumentation { get; set; }
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved
}

/// <summary>
/// Metrics Configuration.
/// </summary>
public class Metrics
{
/// <summary>
/// Gets or sets a value indicating whether AspNet Instrumentation should be enabled.
/// </summary>
public bool DisableAspNetInstrumentation { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Diagnostics;
using Examples.AspNetCore.Models;
using Microsoft.AspNetCore.Mvc;

namespace Examples.AspNetCore.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

public IActionResult Index()
{
return View();
}

public IActionResult Privacy()
{
return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Azure.Monitor.OpenTelemetry.csproj" />
rajkumar-rangaraj marked this conversation as resolved.
Show resolved Hide resolved
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Examples.AspNetCore.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Azure.Monitor.OpenTelemetry;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddAzureMonitorOpenTelemetry();

// This is another overload to call AddAzureMonitorOpenTelemetry with IConfiguration.
// builder.Services.AddAzureMonitorOpenTelemetry(builder.Configuration.GetSection("AzureMonitorOpenTelemetry"));

var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@{
ViewData["Title"] = "Home Page";
}

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<p>Use this page to detail your site's privacy policy.</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
Loading