Skip to content

Commit 1615ef0

Browse files
committed
Adjusted unit-test to handle isolated TelemetryClient
1 parent 57d2e8c commit 1615ef0

File tree

3 files changed

+44
-81
lines changed

3 files changed

+44
-81
lines changed

LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ namespace Microsoft.ApplicationInsights.NLogTarget
3030
public sealed class ApplicationInsightsTarget : TargetWithLayout
3131
{
3232
private TelemetryClient telemetryClient;
33-
private DateTime lastLogEventTime;
33+
private TelemetryConfiguration telemetryConfiguration;
3434
private NLog.Layouts.Layout instrumentationKeyLayout = string.Empty;
3535
private NLog.Layouts.Layout connectionStringLayout = string.Empty;
3636

@@ -68,12 +68,9 @@ public string ConnectionString
6868
public IList<TargetPropertyWithContext> ContextProperties { get; } = new List<TargetPropertyWithContext>();
6969

7070
/// <summary>
71-
/// Gets the logging controller we will be using.
71+
/// Gets or sets the factory for creating TelemetryConfiguration, so unit-tests can override in-memory-channel.
7272
/// </summary>
73-
internal TelemetryClient TelemetryClient
74-
{
75-
get { return this.telemetryClient; }
76-
}
73+
internal Func<TelemetryConfiguration> TelemetryConfigurationFactory { get; set; }
7774

7875
internal void BuildPropertyBag(LogEventInfo logEvent, ITelemetry trace)
7976
{
@@ -119,9 +116,9 @@ internal void BuildPropertyBag(LogEventInfo logEvent, ITelemetry trace)
119116
}
120117

121118
/// <summary>
122-
/// Initializes the Target and perform instrumentationKey validation.
119+
/// Initializes the Target and configures TelemetryClient.
123120
/// </summary>
124-
/// <exception cref="NLogConfigurationException">Will throw when <see cref="InstrumentationKey"/> is not set.</exception>
121+
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "ApplicationInsightsTarget class handles ownership of TelemetryConfiguration with Dispose.")]
125122
protected override void InitializeTarget()
126123
{
127124
base.InitializeTarget();
@@ -132,9 +129,9 @@ protected override void InitializeTarget()
132129
// configure new telemetryclient with the connectionstring otherwise using legacy instrumentationkey.
133130
if (!string.IsNullOrWhiteSpace(connectionString))
134131
{
135-
var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
136-
telemetryConfiguration.ConnectionString = connectionString;
137-
this.telemetryClient = new TelemetryClient(telemetryConfiguration);
132+
this.telemetryConfiguration = this.TelemetryConfigurationFactory?.Invoke() ?? TelemetryConfiguration.CreateDefault();
133+
this.telemetryConfiguration.ConnectionString = connectionString;
134+
this.telemetryClient = new TelemetryClient(this.telemetryConfiguration);
138135
}
139136
else
140137
{
@@ -151,6 +148,17 @@ protected override void InitializeTarget()
151148
this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("nlog:");
152149
}
153150

151+
/// <summary>
152+
/// Closes the target and releases resources used by the current instance of the <see cref="ApplicationInsightsTarget"/> class.
153+
/// </summary>
154+
protected override void CloseTarget()
155+
{
156+
this.telemetryConfiguration?.Dispose();
157+
this.telemetryConfiguration = null;
158+
159+
base.CloseTarget();
160+
}
161+
154162
/// <summary>
155163
/// Send the log message to Application Insights.
156164
/// </summary>
@@ -162,8 +170,6 @@ protected override void Write(LogEventInfo logEvent)
162170
throw new ArgumentNullException(nameof(logEvent));
163171
}
164172

165-
this.lastLogEventTime = DateTime.UtcNow;
166-
167173
if (logEvent.Exception != null)
168174
{
169175
this.SendException(logEvent);
@@ -187,14 +193,29 @@ protected override void FlushAsync(AsyncContinuation asyncContinuation)
187193

188194
try
189195
{
190-
this.TelemetryClient.FlushAsync(System.Threading.CancellationToken.None).ContinueWith(t => asyncContinuation(t.Exception));
196+
this.telemetryClient.FlushAsync(System.Threading.CancellationToken.None).ContinueWith(t => asyncContinuation(t.Exception));
191197
}
192198
catch (Exception ex)
193199
{
194200
asyncContinuation(ex);
195201
}
196202
}
197203

204+
/// <summary>
205+
/// Releases resources used by the current instance of the <see cref="ApplicationInsightsTarget"/> class.
206+
/// </summary>
207+
/// <param name="disposing">Dispose managed state (managed objects).</param>
208+
protected override void Dispose(bool disposing)
209+
{
210+
base.Dispose(disposing);
211+
212+
if (disposing)
213+
{
214+
this.telemetryConfiguration?.Dispose();
215+
this.telemetryConfiguration = null;
216+
}
217+
}
218+
198219
private static void LoadLogEventProperties(LogEventInfo logEvent, IDictionary<string, string> propertyBag)
199220
{
200221
if (logEvent.Properties?.Count > 0)

LOGGING/test/NLogTarget.Tests/NLogTargetTests.cs

Lines changed: 7 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -455,64 +455,14 @@ public void NLogTargetFlushesTelemetryClient()
455455
NLog.Common.AsyncContinuation asyncContinuation = (ex) => { flushException = ex; flushEvent.Set(); };
456456
aiLogger.Factory.Flush(asyncContinuation, 5000);
457457
Assert.IsTrue(flushEvent.WaitOne(5000));
458-
Assert.IsNotNull(flushException);
459-
Assert.AreEqual("Flush called", flushException.Message);
460458
}
461459

462460
[TestMethod]
463461
[TestCategory("NLogTarget")]
464-
public void NLogInfoIsSentAsInformationTraceItemWithAIConnectionString()
462+
public void NLogTargetWithConnectionString()
465463
{
466-
var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString");
467-
aiLogger.Info("Info message");
468-
469-
var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First();
470-
Assert.AreEqual($"Info message", telemetry.Message);
471-
}
472-
473-
[TestMethod]
474-
[TestCategory("NLogTarget")]
475-
public void NLogTraceIsSentAsVerboseTraceItemWithAIConnectionString()
476-
{
477-
var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString");
478-
aiLogger.Trace("Trace message");
479-
480-
var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
481-
Assert.AreEqual("Trace message", telemetry.Message);
482-
}
483-
484-
[TestMethod]
485-
[TestCategory("NLogTarget")]
486-
public void NLogDebugIsSentAsVerboseTraceItemWithAIConnectionString()
487-
{
488-
var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString");
489-
aiLogger.Debug("Debug Message");
490-
491-
var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
492-
Assert.AreEqual("Debug Message", telemetry.Message);
493-
}
494-
495-
[TestMethod]
496-
[TestCategory("NLogTarget")]
497-
public void NLogWarnIsSentAsWarningTraceItemWithAIConnectionString()
498-
{
499-
var aiLogger = this.CreateTargetWithGivenConnectionString("Your_ApplicationInsights_ConnectionString");
500-
501-
aiLogger.Warn("Warn message");
502-
503-
var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
504-
Assert.AreEqual("Warn message", telemetry.Message);
505-
}
506-
507-
[TestMethod]
508-
[TestCategory("NLogTarget")]
509-
public void NLogErrorIsSentAsVerboseTraceItemWithAIConnectionString()
510-
{
511-
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/");
512-
aiLogger.Error("Error Message");
513-
514-
var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
515-
Assert.AreEqual("Error Message", telemetry.Message);
464+
var aiLogger = this.CreateTargetWithGivenConnectionString("TestAI");
465+
VerifyMessagesInMockChannel(aiLogger, "TestAI");
516466
}
517467

518468
private void VerifyMessagesInMockChannel(Logger aiLogger, string instrumentationKey)
@@ -562,19 +512,16 @@ private Logger CreateTargetWithGivenInstrumentationKey(
562512
}
563513

564514
private Logger CreateTargetWithGivenConnectionString(
565-
string connectionString = "Your_ApplicationInsights_ConnectionString",
515+
string instrumentationKey = "TEST",
566516
Action<Logger> loggerAction = null)
567517
{
568-
// Mock channel to validate that our appender is trying to send logs
569-
#pragma warning disable CS0618 // Type or member is obsolete
570-
TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
571-
#pragma warning restore CS0618 // Type or member is obsolete
572-
573518
ApplicationInsightsTarget target = new ApplicationInsightsTarget
574519
{
575-
ConnectionString = connectionString
520+
ConnectionString = $"InstrumentationKey={instrumentationKey};IngestionEndpoint=https://localhost/;LiveEndpoint=https://localhost/"
576521
};
577522

523+
target.TelemetryConfigurationFactory = () => new TelemetryConfiguration() { TelemetryChannel = this.adapterHelper.Channel };
524+
578525
LoggingRule rule = new LoggingRule("*", LogLevel.Trace, target);
579526
LoggingConfiguration config = new LoggingConfiguration();
580527
config.AddTarget("AITarget", target);

LOGGING/test/Shared/AdapterHelper.cs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@ public class AdapterHelper : IDisposable
1919
{
2020
public string InstrumentationKey { get; }
2121

22-
public string ConnectionString { get; }
23-
2422
#if NET452 || NET46
2523
private static readonly string ApplicationInsightsConfigFilePath =
2624
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ApplicationInsights.config");
@@ -29,19 +27,16 @@ public class AdapterHelper : IDisposable
2927
Path.Combine(Path.GetDirectoryName(typeof(AdapterHelper).GetTypeInfo().Assembly.Location), "ApplicationInsights.config");
3028
#endif
3129

32-
public AdapterHelper(string instrumentationKey = "F8474271-D231-45B6-8DD4-D344C309AE69"
33-
, string connectionString = "Your_ApplicationInsights_ConnectionString")
30+
public AdapterHelper(string instrumentationKey = "F8474271-D231-45B6-8DD4-D344C309AE69")
3431
{
3532
this.InstrumentationKey = instrumentationKey;
36-
this.ConnectionString = connectionString;
3733

3834
string configuration = string.Format(InvariantCulture,
3935
@"<?xml version=""1.0"" encoding=""utf-8"" ?>
4036
<ApplicationInsights xmlns=""http://schemas.microsoft.com/ApplicationInsights/2013/Settings"">
4137
<InstrumentationKey>{0}</InstrumentationKey>
4238
</ApplicationInsights>",
43-
instrumentationKey,
44-
connectionString);
39+
instrumentationKey);
4540

4641
File.WriteAllText(ApplicationInsightsConfigFilePath, configuration);
4742
this.Channel = new CustomTelemetryChannel();

0 commit comments

Comments
 (0)