diff --git a/CHANGELOG.md b/CHANGELOG.md index ffed61f1..550074df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Changelog +### Version 2.6.0 +- [NLog Flush should include async delay](https://github.com/Microsoft/ApplicationInsights-dotnet-logging/pull/176) + ### Version 2.6.0-beta3 - [NetStandard Support for TraceListener](https://github.com/Microsoft/ApplicationInsights-dotnet-logging/pull/166) - [NetStandard Support for NLog and log4net](https://github.com/Microsoft/ApplicationInsights-dotnet-logging/pull/167) diff --git a/src/NLogTarget/ApplicationInsightsTarget.cs b/src/NLogTarget/ApplicationInsightsTarget.cs index ca71ee9f..7233d815 100644 --- a/src/NLogTarget/ApplicationInsightsTarget.cs +++ b/src/NLogTarget/ApplicationInsightsTarget.cs @@ -28,6 +28,7 @@ namespace Microsoft.ApplicationInsights.NLogTarget public sealed class ApplicationInsightsTarget : TargetWithLayout { private TelemetryClient telemetryClient; + private DateTime lastLogEventTime; /// /// Initializers a new instance of ApplicationInsightsTarget type. @@ -108,6 +109,8 @@ protected override void Write(LogEventInfo logEvent) throw new ArgumentNullException("logEvent"); } + this.lastLogEventTime = DateTime.UtcNow; + if (logEvent.Exception != null) { this.SendException(logEvent); @@ -127,7 +130,17 @@ protected override void FlushAsync(AsyncContinuation asyncContinuation) try { this.TelemetryClient.Flush(); - asyncContinuation(null); + 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)); + } } catch (Exception ex) {