4
votes

I'm using Microsoft Application Insights in my WPF app and NLog for logging exceptions and debug informations. So, I added Application Insights NLog Target to the app. But all events logged by this NLog target doesn't contain context data on Azure portal.

Other events, logged using TelemetryClient contains these data.

 var telemetryClient = new TelemetryClient();
        telemetryClient.InstrumentationKey = "xxx";
        telemetryClient.Context.User.Id = Environment.UserName;
        telemetryClient.Context.Session.Id = Guid.NewGuid().ToString();

        //var config = new LoggingConfiguration();
        ConfigurationItemFactory.Default.Targets.RegisterDefinition(
                    "ai",
                    typeof(ApplicationInsightsTarget)
                );

        ApplicationInsightsTarget aiTarget = new ApplicationInsightsTarget();
        aiTarget.InstrumentationKey = "xxx";
        aiTarget.Name = "ai";
        LogManager.Configuration.AddTarget("ai", aiTarget);

        LogManager.Configuration.AddRule(LogLevel.Info, LogLevel.Info, aiTarget);

        LogManager.Configuration.Reload();
        LogManager.ReconfigExistingLoggers();

My question is - it is possible to use this context data also for events logged by NLog Target? Or, how can I set context data also for NLog?

1

1 Answers

3
votes

You can use a TelemetryInitializer to ensure that all the items that get created get the context you want?

modified example from: http://apmtips.com/blog/2014/12/01/telemetry-initializers/

namespace ApmTips.Tools
{
    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.Diagnostics.Tracing;
    using System.Diagnostics;

    public class ExtendedIDTelemetryInitializer : ITelemetryInitializer
    {
        public void Initialize(Microsoft.ApplicationInsights.Channel.ITelemetry telemetry)
        {
            telemetry.Context.[some field] = [some value];
        }
    }
}

you'll also need to register that initializer, etc, and the instructions for that are in the post above, there's several ways to do it.

(but don't use a ContextInitializer, it is misnamed from what you'd think it does) and: http://apmtips.com/blog/2015/06/09/do-not-use-context-initializers/