Skip to content

Commit

Permalink
Make TelemetryConfiguration configurable in ApplicationInsightsLoggin…
Browse files Browse the repository at this point in the history
…gBuilderExtensions (#2552)

* Make TelemetryConfiguration configurable

* public api

* update test

* update doc examples

* fix doc

* fix whitespace
  • Loading branch information
TimothyMothra authored Mar 10, 2022
1 parent c0b8fd8 commit ed0015a
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
static Microsoft.Extensions.Logging.ApplicationInsightsLoggingBuilderExtensions.AddApplicationInsights(this Microsoft.Extensions.Logging.ILoggingBuilder builder, System.Action<Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration> configureTelemetryConfiguration, System.Action<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerOptions> configureApplicationInsightsLoggerOptions) -> Microsoft.Extensions.Logging.ILoggingBuilder
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Changelog

## VNext

- [LOGGING: Make TelemetryConfiguration configurable in ApplicationInsightsLoggingBuilderExtensions](https://github.com/microsoft/ApplicationInsights-dotnet/issues/1944)

## Version 2.21.0-beta1
- [Support IPv6 in request headers](https://github.com/microsoft/ApplicationInsights-dotnet/issues/2521)
Expand Down
2 changes: 1 addition & 1 deletion LOGGING/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Read more:
- [Microsoft Docs: "Diagnose sudden changes in your app telemetry"](https://docs.microsoft.com/azure/application-insights/app-insights-analytics-diagnostics#trace)

## ILogger
See [this](https://github.com/Microsoft/ApplicationInsights-dotnet-logging/tree/develop/src/ILogger/Readme.md).
See [this](src/ILogger/Readme.md).

## NLog

Expand Down
13 changes: 11 additions & 2 deletions LOGGING/src/ILogger/ApplicationInsightsLoggingBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,17 +93,26 @@ public static ILoggingBuilder AddApplicationInsights(
/// <param name="builder">The <see cref="ILoggingBuilder"/> to use.</param>
/// <param name="configureTelemetryConfiguration">Action to configure telemetry configuration.</param>
/// <param name="configureApplicationInsightsLoggerOptions">Action to configure ApplicationInsights logger.</param>
private static ILoggingBuilder AddApplicationInsights(
public static ILoggingBuilder AddApplicationInsights(
this ILoggingBuilder builder,
Action<TelemetryConfiguration> configureTelemetryConfiguration,
Action<ApplicationInsightsLoggerOptions> configureApplicationInsightsLoggerOptions)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}

if (configureTelemetryConfiguration == null)
{
throw new ArgumentNullException(nameof(configureTelemetryConfiguration));
}

if (configureApplicationInsightsLoggerOptions == null)
{
throw new ArgumentNullException(nameof(configureApplicationInsightsLoggerOptions));
}

// Initialize IOptions<TelemetryConfiguration> user can keep on configuring it furthur if they want to.
builder.Services.Configure<TelemetryConfiguration>(configureTelemetryConfiguration);

builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, ApplicationInsightsLoggerProvider>());
Expand Down
33 changes: 17 additions & 16 deletions LOGGING/src/ILogger/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ class Program
// Add the logging pipelines to use. We are using Application Insights only here.
services.AddLogging(loggingBuilder =>
{
// Optional: Apply filters to configure LogLevel Trace or above is sent to ApplicationInsights for all
// categories.
loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
loggingBuilder.AddApplicationInsights("--YourAIKeyHere--");
// Optional: Apply filters to configure LogLevel Trace or above is sent to ApplicationInsights for all categories.
loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);

loggingBuilder.AddApplicationInsights(
telemetryConfiguration => { telemetryConfiguration.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000"; },
applicationInsightsLoggerOptions => { });
});

// Build ServiceProvider.
Expand Down Expand Up @@ -68,15 +70,15 @@ public class Program
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.AddApplicationInsights("ikeyhere");
loggingBuilder.AddApplicationInsights(
telemetryConfiguration => { telemetryConfiguration.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000"; },
applicationInsightsLoggerOptions => { });

// Optional: Apply filters to configure LogLevel Trace or above is sent to
// ApplicationInsights for all categories.
// Optional: Apply filters to configure LogLevel Trace or above is sent to ApplicationInsights for all categories.
logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);

// Additional filtering For category starting in "Microsoft",
// only Warning or above will be sent to Application Insights.
logging.AddFilter<ApplicationInsightsLoggerProvider>("Microsoft", LogLevel.Warning);
// Additional filtering For category starting in "Microsoft", only Warning or above will be sent to Application Insights.
logging.AddFilter<ApplicationInsightsLoggerProvider>("Microsoft", LogLevel.Warning);
})
.Build();
}
Expand Down Expand Up @@ -138,13 +140,12 @@ public class ValuesController : ControllerBase
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
// All the following logs will be picked upby Application Insights.
// and all have ("MyKey", "MyValue") in Properties.
using (_logger.BeginScope(new Dictionary<string, object> { { "MyKey", "MyValue" } }))
// All the following logs will be picked upby Application Insights and all have ("MyKey", "MyValue") in Properties.
using (_logger.BeginScope(new Dictionary<string, object> { { "MyKey", "MyValue" } }))
{
_logger.LogInformation("This is an information trace..");
_logger.LogWarning("This is a warning trace..");
_logger.LogTrace("this is a Trace level message");
_logger.LogInformation("This is an information trace..");
_logger.LogWarning("This is a warning trace..");
_logger.LogTrace("this is a Trace level message");
}

return new string[] { "value1", "value2" };
Expand Down
24 changes: 24 additions & 0 deletions LOGGING/test/ILogger.Tests/ILoggerIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,30 @@ public void ApplicationInsightsLoggerInstrumentationKeyIsSetCorrectly()
Assert.AreEqual("TestAIKey", telemetryConfiguration.InstrumentationKey);
}

/// <summary>
/// Test to ensure TelemetryConfiguration is set correctly.
/// </summary>
[TestMethod]
[TestCategory("ILogger")]
public void ApplicationInsightsLoggerTelemetryConfigurationIsSetCorrectly()
{
// Create DI container.
IServiceCollection services = new ServiceCollection();

services.AddLogging(loggingBuilder =>
{
loggingBuilder.AddApplicationInsights(
telemetryConfiguration => { telemetryConfiguration.ConnectionString = "InstrumentationKey=TestAIKey"; },
applicationInsightsLoggerOptions => { });
});

TelemetryConfiguration actualTelemetryConfiguration = services
.BuildServiceProvider()
.GetRequiredService<IOptions<TelemetryConfiguration>>().Value;

Assert.AreEqual("TestAIKey", actualTelemetryConfiguration.InstrumentationKey);
}

/// <summary>
/// Ensures that the default <see cref="ApplicationInsightsLoggerOptions"/> are as expected.
/// </summary>
Expand Down

0 comments on commit ed0015a

Please sign in to comment.