From d005129a76991f6bca33e54a69a2ad14ddf3ef05 Mon Sep 17 00:00:00 2001 From: saidi-adot Date: Tue, 19 Mar 2024 13:10:24 -0700 Subject: [PATCH 1/5] Add support for connection string to Microsoft.ApplicationInsights.NLogTarget --- .../net452/PublicAPI.Shipped.txt | 2 + LOGGING/README.md | 28 +++++- .../NLogTarget/ApplicationInsightsTarget.cs | 28 +++++- .../test/NLogTarget.Tests/NLogTargetTests.cs | 90 ++++++++++++++++++- LOGGING/test/Shared/AdapterHelper.cs | 9 +- 5 files changed, 150 insertions(+), 7 deletions(-) diff --git a/.publicApi/Microsoft.ApplicationInsights.NLogTarget.dll/net452/PublicAPI.Shipped.txt b/.publicApi/Microsoft.ApplicationInsights.NLogTarget.dll/net452/PublicAPI.Shipped.txt index 1fa6d1888c..8471af83e6 100644 --- a/.publicApi/Microsoft.ApplicationInsights.NLogTarget.dll/net452/PublicAPI.Shipped.txt +++ b/.publicApi/Microsoft.ApplicationInsights.NLogTarget.dll/net452/PublicAPI.Shipped.txt @@ -3,6 +3,8 @@ Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.ApplicationIn Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.ContextProperties.get -> System.Collections.Generic.IList Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.InstrumentationKey.get -> string Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.InstrumentationKey.set -> void +Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.ConnectionString.get -> string +Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.ConnectionString.set -> void Microsoft.ApplicationInsights.NLogTarget.TargetPropertyWithContext Microsoft.ApplicationInsights.NLogTarget.TargetPropertyWithContext.Layout.get -> NLog.Layouts.Layout Microsoft.ApplicationInsights.NLogTarget.TargetPropertyWithContext.Layout.set -> void diff --git a/LOGGING/README.md b/LOGGING/README.md index c022877113..8eeaae1e2e 100644 --- a/LOGGING/README.md +++ b/LOGGING/README.md @@ -37,7 +37,26 @@ Application Insights NLog Target nuget package adds ApplicationInsights target i If your application does not have web.config then it can also be configured manually. - * **Configure ApplicationInsightsTarget using NLog.config** : +* **Configure ApplicationInsightsTarget with ConnectionString using NLog.config** : +ConnectionString is the preferred approach to write logs into Application Insights. If the NLog Application Insights target has connectionString in the config file then TelemetryClient will use it, otherwise it will use the instrumentationKey. + +```xml + + + + + + + Your_ApplicationInsights_ConnectionString + + + + + + + +``` + * **Configure ApplicationInsightsTarget using NLog.config** : ```xml @@ -70,6 +89,10 @@ For more information see: ```csharp +// You need this only if you did not define ConnectionString or InstrumentationKey in ApplicationInsights.config (Or in the NLog.config) +TelemetryConfiguration.Active.ConnectionString = "Your_ApplicationInsights_ConnectionString"; + +or // You need this only if you did not define InstrumentationKey in ApplicationInsights.config (Or in the NLog.config) TelemetryConfiguration.Active.InstrumentationKey = "Your_Resource_Key"; @@ -85,6 +108,9 @@ If you configure NLog programmatically with the [NLog Config API](https://github var config = new LoggingConfiguration(); ApplicationInsightsTarget target = new ApplicationInsightsTarget(); +// You need this only if you did not define Application Insights ConnectionString in ApplicationInsights.config or want to use different connectionstring +target.ConnectionString = "Your_ApplicationInsights_ConnectionString"; +or // You need this only if you did not define InstrumentationKey in ApplicationInsights.config or want to use different instrumentation key target.InstrumentationKey = "Your_Resource_Key"; diff --git a/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs b/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs index 7d5e65d079..a20f7c9dbc 100644 --- a/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs +++ b/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs @@ -13,6 +13,7 @@ namespace Microsoft.ApplicationInsights.NLogTarget using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; + using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.ApplicationInsights.Implementation; @@ -31,6 +32,7 @@ public sealed class ApplicationInsightsTarget : TargetWithLayout private TelemetryClient telemetryClient; private DateTime lastLogEventTime; private NLog.Layouts.Layout instrumentationKeyLayout = string.Empty; + private NLog.Layouts.Layout connectionStringLayout = string.Empty; /// /// Initializers a new instance of ApplicationInsightsTarget type. @@ -50,6 +52,15 @@ public string InstrumentationKey set => this.instrumentationKeyLayout = value ?? string.Empty; } + /// + /// Gets or sets the Application Insights connectionstring for your application. + /// + public string ConnectionString + { + get => (this.connectionStringLayout as NLog.Layouts.SimpleLayout)?.Text ?? null; + set => this.connectionStringLayout = value ?? string.Empty; + } + /// /// Gets the array of custom attributes to be passed into the logevent context. /// @@ -118,10 +129,21 @@ protected override void InitializeTarget() this.telemetryClient = new TelemetryClient(); #pragma warning restore CS0618 // Type or member is obsolete - string instrumentationKey = this.instrumentationKeyLayout.Render(LogEventInfo.CreateNullEvent()); - if (!string.IsNullOrWhiteSpace(instrumentationKey)) + string connectionString = this.connectionStringLayout.Render(LogEventInfo.CreateNullEvent()); + + // Check if nlog application insights target has connectionstring in config file then + // configure telemetryclient with the connectionstring otherwise using instrumentationkey. + if (!string.IsNullOrWhiteSpace(connectionString)) { - this.telemetryClient.Context.InstrumentationKey = instrumentationKey; + this.telemetryClient.TelemetryConfiguration.ConnectionString = connectionString; + } + else + { + string instrumentationKey = this.instrumentationKeyLayout.Render(LogEventInfo.CreateNullEvent()); + if (!string.IsNullOrWhiteSpace(instrumentationKey)) + { + this.telemetryClient.Context.InstrumentationKey = instrumentationKey; + } } this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("nlog:"); diff --git a/LOGGING/test/NLogTarget.Tests/NLogTargetTests.cs b/LOGGING/test/NLogTarget.Tests/NLogTargetTests.cs index 92a6604fd7..bab41820f9 100644 --- a/LOGGING/test/NLogTarget.Tests/NLogTargetTests.cs +++ b/LOGGING/test/NLogTarget.Tests/NLogTargetTests.cs @@ -230,7 +230,7 @@ public void TraceHasCustomProperties() } - [TestMethod] + [TestMethod] [TestCategory("NLogTarget")] public void GlobalDiagnosticContextPropertiesAreAddedToProperties() { @@ -459,6 +459,62 @@ public void NLogTargetFlushesTelemetryClient() Assert.AreEqual("Flush called", flushException.Message); } + [TestMethod] + [TestCategory("NLogTarget")] + public void NLogInfoIsSentAsInformationTraceItemWithAIConnectionString() + { + var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString"); + aiLogger.Info("Info message"); + + var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First(); + Assert.AreEqual($"Info message", telemetry.Message); + } + + [TestMethod] + [TestCategory("NLogTarget")] + public void NLogTraceIsSentAsVerboseTraceItemWithAIConnectionString() + { + var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString"); + aiLogger.Trace("Trace message"); + + var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault(); + Assert.AreEqual("Trace message", telemetry.Message); + } + + [TestMethod] + [TestCategory("NLogTarget")] + public void NLogDebugIsSentAsVerboseTraceItemWithAIConnectionString() + { + var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString"); + aiLogger.Debug("Debug Message"); + + var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault(); + Assert.AreEqual("Debug Message", telemetry.Message); + } + + [TestMethod] + [TestCategory("NLogTarget")] + public void NLogWarnIsSentAsWarningTraceItemWithAIConnectionString() + { + var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString"); + + aiLogger.Warn("Warn message"); + + var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault(); + Assert.AreEqual("Warn message", telemetry.Message); + } + + [TestMethod] + [TestCategory("NLogTarget")] + public void NLogErrorIsSentAsVerboseTraceItemWithAIConnectionString() + { + var aiLogger = this.CreateTargetWithGivenConnectionString("InstrumentationKey=b91a8f48-c77c-4f12-80e2-f96bc1abb126;IngestionEndpoint=https://centralus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://centralus.livediagnostics.monitor.azure.com/"); + aiLogger.Error("Error Message"); + + var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault(); + Assert.AreEqual("Error Message", telemetry.Message); + } + private void VerifyMessagesInMockChannel(Logger aiLogger, string instrumentationKey) { aiLogger.Trace("Sample trace message"); @@ -504,5 +560,37 @@ private Logger CreateTargetWithGivenInstrumentationKey( return aiLogger; } + + private Logger CreateTargetWithGivenConnectionString( + string connectionString = "Your_ApplicationInsights_ConnectionString", + Action loggerAction = null) + { + // Mock channel to validate that our appender is trying to send logs +#pragma warning disable CS0618 // Type or member is obsolete + TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel; +#pragma warning restore CS0618 // Type or member is obsolete + + ApplicationInsightsTarget target = new ApplicationInsightsTarget + { + ConnectionString = connectionString + }; + + LoggingRule rule = new LoggingRule("*", LogLevel.Trace, target); + LoggingConfiguration config = new LoggingConfiguration(); + config.AddTarget("AITarget", target); + config.LoggingRules.Add(rule); + + LogManager.Configuration = config; + Logger aiLogger = LogManager.GetLogger("AITarget"); + + if (loggerAction != null) + { + loggerAction(aiLogger); + target.Dispose(); + return null; + } + + return aiLogger; + } } } diff --git a/LOGGING/test/Shared/AdapterHelper.cs b/LOGGING/test/Shared/AdapterHelper.cs index 9b926f8599..9106afb3f8 100644 --- a/LOGGING/test/Shared/AdapterHelper.cs +++ b/LOGGING/test/Shared/AdapterHelper.cs @@ -19,6 +19,8 @@ public class AdapterHelper : IDisposable { public string InstrumentationKey { get; } + public string ConnectionString { get; } + #if NET452 || NET46 private static readonly string ApplicationInsightsConfigFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ApplicationInsights.config"); @@ -27,16 +29,19 @@ public class AdapterHelper : IDisposable Path.Combine(Path.GetDirectoryName(typeof(AdapterHelper).GetTypeInfo().Assembly.Location), "ApplicationInsights.config"); #endif - public AdapterHelper(string instrumentationKey = "F8474271-D231-45B6-8DD4-D344C309AE69") + public AdapterHelper(string instrumentationKey = "F8474271-D231-45B6-8DD4-D344C309AE69" + , string connectionString = "Your_ApplicationInsights_ConnectionString") { this.InstrumentationKey = instrumentationKey; + this.ConnectionString = connectionString; string configuration = string.Format(InvariantCulture, @" {0} ", - instrumentationKey); + instrumentationKey, + connectionString); File.WriteAllText(ApplicationInsightsConfigFilePath, configuration); this.Channel = new CustomTelemetryChannel(); From e4a0e8b7f5442334be965151f6fde2f1ee97691f Mon Sep 17 00:00:00 2001 From: saidi-adot Date: Tue, 19 Mar 2024 14:05:20 -0700 Subject: [PATCH 2/5] Update PublicAPI.Shipped.txt Adding new methods to Public Api --- .../netstandard2.0/PublicAPI.Shipped.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.publicApi/Microsoft.ApplicationInsights.NLogTarget.dll/netstandard2.0/PublicAPI.Shipped.txt b/.publicApi/Microsoft.ApplicationInsights.NLogTarget.dll/netstandard2.0/PublicAPI.Shipped.txt index 1fa6d1888c..8471af83e6 100644 --- a/.publicApi/Microsoft.ApplicationInsights.NLogTarget.dll/netstandard2.0/PublicAPI.Shipped.txt +++ b/.publicApi/Microsoft.ApplicationInsights.NLogTarget.dll/netstandard2.0/PublicAPI.Shipped.txt @@ -3,6 +3,8 @@ Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.ApplicationIn Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.ContextProperties.get -> System.Collections.Generic.IList Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.InstrumentationKey.get -> string Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.InstrumentationKey.set -> void +Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.ConnectionString.get -> string +Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget.ConnectionString.set -> void Microsoft.ApplicationInsights.NLogTarget.TargetPropertyWithContext Microsoft.ApplicationInsights.NLogTarget.TargetPropertyWithContext.Layout.get -> NLog.Layouts.Layout Microsoft.ApplicationInsights.NLogTarget.TargetPropertyWithContext.Layout.set -> void From e623c1bf9ae1f4f8c3819bc43a6f233c0bfccef4 Mon Sep 17 00:00:00 2001 From: Rolf Kristensen Date: Tue, 13 Aug 2024 21:38:32 +0200 Subject: [PATCH 3/5] NLogTarget - Use isolated TelemetryClient instead of modifying global config --- LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs b/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs index a20f7c9dbc..de6a5a77a0 100644 --- a/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs +++ b/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs @@ -125,20 +125,22 @@ internal void BuildPropertyBag(LogEventInfo logEvent, ITelemetry trace) protected override void InitializeTarget() { base.InitializeTarget(); -#pragma warning disable CS0618 // Type or member is obsolete: TelemtryConfiguration.Active is used in TelemetryClient constructor. - this.telemetryClient = new TelemetryClient(); -#pragma warning restore CS0618 // Type or member is obsolete string connectionString = this.connectionStringLayout.Render(LogEventInfo.CreateNullEvent()); // Check if nlog application insights target has connectionstring in config file then - // configure telemetryclient with the connectionstring otherwise using instrumentationkey. + // configure new telemetryclient with the connectionstring otherwise using legacy instrumentationkey. if (!string.IsNullOrWhiteSpace(connectionString)) { - this.telemetryClient.TelemetryConfiguration.ConnectionString = connectionString; + var telemetryConfiguration = TelemetryConfiguration.CreateDefault(); + telemetryConfiguration.ConnectionString = connectionString; + this.telemetryClient = new TelemetryClient(telemetryConfiguration); } else { +#pragma warning disable CS0618 // Type or member is obsolete: TelemtryConfiguration.Active is used in TelemetryClient constructor. + this.telemetryClient = new TelemetryClient(); +#pragma warning restore CS0618 // Type or member is obsolete string instrumentationKey = this.instrumentationKeyLayout.Render(LogEventInfo.CreateNullEvent()); if (!string.IsNullOrWhiteSpace(instrumentationKey)) { From ea79e58102af5a3355a4f92e228d6e9877aadd8c Mon Sep 17 00:00:00 2001 From: Rolf Kristensen Date: Tue, 13 Aug 2024 21:46:49 +0200 Subject: [PATCH 4/5] NLogTarget - Use FlushAsync instead of synchronous --- CHANGELOG.md | 1 + LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs | 13 +------------ 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 049c0f363d..5d2dd920f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## VNext - [Populate required field Message with "n/a" if it is empty](https://github.com/microsoft/ApplicationInsights-dotnet/issues/1066) +- [NLog Target with support for specifying ConnectionString](https://github.com/microsoft/ApplicationInsights-dotnet/issues/2897) ## Version 2.22.0 - no changes since beta. diff --git a/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs b/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs index de6a5a77a0..d4ba9304a7 100644 --- a/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs +++ b/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs @@ -187,18 +187,7 @@ protected override void FlushAsync(AsyncContinuation asyncContinuation) try { - this.TelemetryClient.Flush(); - if (DateTime.UtcNow.AddSeconds(-30) > this.lastLogEventTime) - { - // Nothing has been written, so nothing to wait for - asyncContinuation(null); - } - else - { - // Documentation says it is important to wait after flush, else nothing will happen - // https://docs.microsoft.com/azure/application-insights/app-insights-api-custom-events-metrics#flushing-data - System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(500)).ContinueWith((task) => asyncContinuation(null)); - } + this.TelemetryClient.FlushAsync(System.Threading.CancellationToken.None).ContinueWith(t => asyncContinuation(t.Exception)); } catch (Exception ex) { From df344635f2b5aee4dc9152a029b87854430b2116 Mon Sep 17 00:00:00 2001 From: Rolf Kristensen Date: Tue, 13 Aug 2024 22:22:06 +0200 Subject: [PATCH 5/5] Adjusted unit-test to handle isolated TelemetryClient --- .../NLogTarget/ApplicationInsightsTarget.cs | 49 ++++++++++---- .../test/NLogTarget.Tests/NLogTargetTests.cs | 67 ++----------------- LOGGING/test/Shared/AdapterHelper.cs | 9 +-- 3 files changed, 44 insertions(+), 81 deletions(-) diff --git a/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs b/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs index d4ba9304a7..9d94ff70cf 100644 --- a/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs +++ b/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs @@ -30,7 +30,7 @@ namespace Microsoft.ApplicationInsights.NLogTarget public sealed class ApplicationInsightsTarget : TargetWithLayout { private TelemetryClient telemetryClient; - private DateTime lastLogEventTime; + private TelemetryConfiguration telemetryConfiguration; private NLog.Layouts.Layout instrumentationKeyLayout = string.Empty; private NLog.Layouts.Layout connectionStringLayout = string.Empty; @@ -68,12 +68,9 @@ public string ConnectionString public IList ContextProperties { get; } = new List(); /// - /// Gets the logging controller we will be using. + /// Gets or sets the factory for creating TelemetryConfiguration, so unit-tests can override in-memory-channel. /// - internal TelemetryClient TelemetryClient - { - get { return this.telemetryClient; } - } + internal Func TelemetryConfigurationFactory { get; set; } internal void BuildPropertyBag(LogEventInfo logEvent, ITelemetry trace) { @@ -119,9 +116,9 @@ internal void BuildPropertyBag(LogEventInfo logEvent, ITelemetry trace) } /// - /// Initializes the Target and perform instrumentationKey validation. + /// Initializes the Target and configures TelemetryClient. /// - /// Will throw when is not set. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "ApplicationInsightsTarget class handles ownership of TelemetryConfiguration with Dispose.")] protected override void InitializeTarget() { base.InitializeTarget(); @@ -132,9 +129,9 @@ protected override void InitializeTarget() // configure new telemetryclient with the connectionstring otherwise using legacy instrumentationkey. if (!string.IsNullOrWhiteSpace(connectionString)) { - var telemetryConfiguration = TelemetryConfiguration.CreateDefault(); - telemetryConfiguration.ConnectionString = connectionString; - this.telemetryClient = new TelemetryClient(telemetryConfiguration); + this.telemetryConfiguration = this.TelemetryConfigurationFactory?.Invoke() ?? TelemetryConfiguration.CreateDefault(); + this.telemetryConfiguration.ConnectionString = connectionString; + this.telemetryClient = new TelemetryClient(this.telemetryConfiguration); } else { @@ -151,6 +148,17 @@ protected override void InitializeTarget() this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("nlog:"); } + /// + /// Closes the target and releases resources used by the current instance of the class. + /// + protected override void CloseTarget() + { + this.telemetryConfiguration?.Dispose(); + this.telemetryConfiguration = null; + + base.CloseTarget(); + } + /// /// Send the log message to Application Insights. /// @@ -162,8 +170,6 @@ protected override void Write(LogEventInfo logEvent) throw new ArgumentNullException(nameof(logEvent)); } - this.lastLogEventTime = DateTime.UtcNow; - if (logEvent.Exception != null) { this.SendException(logEvent); @@ -187,7 +193,7 @@ protected override void FlushAsync(AsyncContinuation asyncContinuation) try { - this.TelemetryClient.FlushAsync(System.Threading.CancellationToken.None).ContinueWith(t => asyncContinuation(t.Exception)); + this.telemetryClient.FlushAsync(System.Threading.CancellationToken.None).ContinueWith(t => asyncContinuation(t.Exception)); } catch (Exception ex) { @@ -195,6 +201,21 @@ protected override void FlushAsync(AsyncContinuation asyncContinuation) } } + /// + /// Releases resources used by the current instance of the class. + /// + /// Dispose managed state (managed objects). + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (disposing) + { + this.telemetryConfiguration?.Dispose(); + this.telemetryConfiguration = null; + } + } + private static void LoadLogEventProperties(LogEventInfo logEvent, IDictionary propertyBag) { if (logEvent.Properties?.Count > 0) diff --git a/LOGGING/test/NLogTarget.Tests/NLogTargetTests.cs b/LOGGING/test/NLogTarget.Tests/NLogTargetTests.cs index bab41820f9..a2ab9a86c1 100644 --- a/LOGGING/test/NLogTarget.Tests/NLogTargetTests.cs +++ b/LOGGING/test/NLogTarget.Tests/NLogTargetTests.cs @@ -455,64 +455,14 @@ public void NLogTargetFlushesTelemetryClient() NLog.Common.AsyncContinuation asyncContinuation = (ex) => { flushException = ex; flushEvent.Set(); }; aiLogger.Factory.Flush(asyncContinuation, 5000); Assert.IsTrue(flushEvent.WaitOne(5000)); - Assert.IsNotNull(flushException); - Assert.AreEqual("Flush called", flushException.Message); } [TestMethod] [TestCategory("NLogTarget")] - public void NLogInfoIsSentAsInformationTraceItemWithAIConnectionString() + public void NLogTargetWithConnectionString() { - var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString"); - aiLogger.Info("Info message"); - - var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First(); - Assert.AreEqual($"Info message", telemetry.Message); - } - - [TestMethod] - [TestCategory("NLogTarget")] - public void NLogTraceIsSentAsVerboseTraceItemWithAIConnectionString() - { - var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString"); - aiLogger.Trace("Trace message"); - - var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault(); - Assert.AreEqual("Trace message", telemetry.Message); - } - - [TestMethod] - [TestCategory("NLogTarget")] - public void NLogDebugIsSentAsVerboseTraceItemWithAIConnectionString() - { - var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString"); - aiLogger.Debug("Debug Message"); - - var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault(); - Assert.AreEqual("Debug Message", telemetry.Message); - } - - [TestMethod] - [TestCategory("NLogTarget")] - public void NLogWarnIsSentAsWarningTraceItemWithAIConnectionString() - { - var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString"); - - aiLogger.Warn("Warn message"); - - var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault(); - Assert.AreEqual("Warn message", telemetry.Message); - } - - [TestMethod] - [TestCategory("NLogTarget")] - public void NLogErrorIsSentAsVerboseTraceItemWithAIConnectionString() - { - var aiLogger = this.CreateTargetWithGivenConnectionString("InstrumentationKey=b91a8f48-c77c-4f12-80e2-f96bc1abb126;IngestionEndpoint=https://centralus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://centralus.livediagnostics.monitor.azure.com/"); - aiLogger.Error("Error Message"); - - var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault(); - Assert.AreEqual("Error Message", telemetry.Message); + var aiLogger = this.CreateTargetWithGivenConnectionString("TestAI"); + VerifyMessagesInMockChannel(aiLogger, "TestAI"); } private void VerifyMessagesInMockChannel(Logger aiLogger, string instrumentationKey) @@ -562,19 +512,16 @@ private Logger CreateTargetWithGivenInstrumentationKey( } private Logger CreateTargetWithGivenConnectionString( - string connectionString = "Your_ApplicationInsights_ConnectionString", + string instrumentationKey = "TEST", Action loggerAction = null) { - // Mock channel to validate that our appender is trying to send logs -#pragma warning disable CS0618 // Type or member is obsolete - TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel; -#pragma warning restore CS0618 // Type or member is obsolete - ApplicationInsightsTarget target = new ApplicationInsightsTarget { - ConnectionString = connectionString + ConnectionString = $"InstrumentationKey={instrumentationKey};IngestionEndpoint=https://localhost/;LiveEndpoint=https://localhost/" }; + target.TelemetryConfigurationFactory = () => new TelemetryConfiguration() { TelemetryChannel = this.adapterHelper.Channel }; + LoggingRule rule = new LoggingRule("*", LogLevel.Trace, target); LoggingConfiguration config = new LoggingConfiguration(); config.AddTarget("AITarget", target); diff --git a/LOGGING/test/Shared/AdapterHelper.cs b/LOGGING/test/Shared/AdapterHelper.cs index 9106afb3f8..9b926f8599 100644 --- a/LOGGING/test/Shared/AdapterHelper.cs +++ b/LOGGING/test/Shared/AdapterHelper.cs @@ -19,8 +19,6 @@ public class AdapterHelper : IDisposable { public string InstrumentationKey { get; } - public string ConnectionString { get; } - #if NET452 || NET46 private static readonly string ApplicationInsightsConfigFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ApplicationInsights.config"); @@ -29,19 +27,16 @@ public class AdapterHelper : IDisposable Path.Combine(Path.GetDirectoryName(typeof(AdapterHelper).GetTypeInfo().Assembly.Location), "ApplicationInsights.config"); #endif - public AdapterHelper(string instrumentationKey = "F8474271-D231-45B6-8DD4-D344C309AE69" - , string connectionString = "Your_ApplicationInsights_ConnectionString") + public AdapterHelper(string instrumentationKey = "F8474271-D231-45B6-8DD4-D344C309AE69") { this.InstrumentationKey = instrumentationKey; - this.ConnectionString = connectionString; string configuration = string.Format(InvariantCulture, @" {0} ", - instrumentationKey, - connectionString); + instrumentationKey); File.WriteAllText(ApplicationInsightsConfigFilePath, configuration); this.Channel = new CustomTelemetryChannel();