0

I have written a error handling framework using ILoggerFactory in .Net Framework 4.8
It supports multiple providers including Application Insights.

Recently I checked the Application Insights Logs and observed that none of my logs are not logging into the app insights.

  1. I was in the correct directory
  2. I have set data sampling to 100%
  3. I have configured the correct connection string
  4. I have installed Fiddler and checked if the request is hitting the Ingestion Endpoint and it does, but it had no response body.Image 1
  5. When called the IngestionEndpoint via powershell, it appeared in the portal.and it had a response body. Image 2
  6. My Code
public AbcExceptionLogger(string categoryName)
{
    _categoryName = categoryName;
    var minimumLogLevelSetting = ConfigurationManager.AppSettings["MinimumLogLevel"];
    if (!Enum.TryParse(minimumLogLevelSetting, true, out _minimumLogLevel))
    {
        _minimumLogLevel = LogLevel.Warning; // Default to Warning if the setting is not a valid LogLevel
    }

    // Create a new logger factory instance
    _loggerFactory = new LoggerFactory();
    var loggerProviderKey = ConfigurationManager.AppSettings["LoggerProvider"];

    if (loggerProviderKey == "ApplicationInsights")
    {
        var appInsightsConnectionString = ConfigurationManager.AppSettings["ApplicationInsights:ConnectionString"];
        //if (!string.IsNullOrEmpty(appInsightsConnectionString))
        //{
        //    IOptions<TelemetryConfiguration> telemetryConfigurationOptions = Options.Create(new TelemetryConfiguration()
        //    {
        //        ConnectionString = appInsightsConnectionString,
        //        TelemetryInitializers = { new AbcTelemetryInitializer() }
        //    });

        //    IOptions<ApplicationInsightsLoggerOptions> applicationInsightsLoggerOptions = Options.Create(new ApplicationInsightsLoggerOptions());


        //    // Add the ApplicationInsightsLoggerProvider to the logger factory
        //    _loggerFactory.AddProvider(new ApplicationInsightsLoggerProvider(
        //        telemetryConfigurationOptions,
        //        applicationInsightsLoggerOptions));
        //}

        var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
        telemetryConfiguration.ConnectionString = appInsightsConnectionString;

        var telemetryInitializer = new AbcTelemetryInitializer();
        telemetryConfiguration.TelemetryInitializers.Add(telemetryInitializer);

        var telemetryConfigOptions = Options.Create(telemetryConfiguration);

        var options = new ApplicationInsightsLoggerOptions();
        var appInsightsLoggerOptions = Options.Create(options);


        telemetryConfiguration.TelemetryChannel = new InMemoryChannel
        {
            DeveloperMode = true
        };

        var aiLoggerProvider = new ApplicationInsightsLoggerProvider(telemetryConfigOptions, appInsightsLoggerOptions);

        _loggerFactory.AddProvider(aiLoggerProvider);


    }

    else if (loggerProviderKey == "Serilog")
    {
        // Create a new logger that enriches log events with the category name
        var serilogLogger = SerilogLoggerSingleton.Instance.ForContext("CategoryName", _categoryName);

        _loggerFactory.AddProvider(new Serilog.Extensions.Logging.SerilogLoggerProvider(serilogLogger));
    }
    else if (loggerProviderKey == "Log4Net")
    {
        //Add Log4Net provider to the logger factory
        _loggerFactory.AddProvider(new Log4NetProvider());
    }
    else
    {
        // Add the default logger provider to the logger factory

    }

    // Create a new logger instance using the logger factory
    _logger = _loggerFactory.CreateLogger(_categoryName);

}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
    
    if (!IsEnabled(logLevel))
    {
        return;
    }

    // Create a new logger instance using the logger factory
    //var logger = _loggerFactory.CreateLogger(_categoryName);

    // Log the message using the logger instance
    _logger.Log(logLevel, eventId, state, exception, formatter);

}

My AbcTelemetryInitializer

public class AbcTelemetryInitializer: ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        var httpContext = HttpContext.Current;
        if (httpContext != null)
        {
            var request = httpContext.Request;

            // Add context data from HttpContext
            telemetry.Context.GlobalProperties["HttpMethod"] = request.HttpMethod;
            telemetry.Context.GlobalProperties["Url.Scheme"] = request.Url.Scheme;
            telemetry.Context.GlobalProperties["Url.Host"] = request.Url.Host;
            telemetry.Context.GlobalProperties["Url.AbsolutePath"] = request.Url.AbsolutePath;
            telemetry.Context.GlobalProperties["Url.AbsoluteUri"] = request.Url.AbsoluteUri;
            telemetry.Context.GlobalProperties["Url.Query"] = request.Url.Query;
            telemetry.Context.GlobalProperties["Url.IsDefaultPort"] = request.Url.IsDefaultPort.ToString();
            telemetry.Context.GlobalProperties["DomainName"] = request.Url.Host;

            // Add session ID if available
            var sessionId = httpContext.Session?.SessionID;
            if (sessionId != null)
            {
                telemetry.Context.GlobalProperties["SessionId"] = sessionId;
            }

            //Add browser info
            var browser = request.Browser;
            telemetry.Context.GlobalProperties["User.Browser"] = string.Format("{0} {1}", browser.Browser, browser.Version);
            telemetry.Context.GlobalProperties["User.Platform"] = browser.Platform;
            telemetry.Context.GlobalProperties["User.Agent"] = request.UserAgent;
            telemetry.Context.GlobalProperties["User.IsMobile"] = browser.IsMobileDevice.ToString();

        }

        // Add module id if available
        var moduleID = ConfigurationManager.AppSettings["ModuleID"];
        if (!string.IsNullOrEmpty(moduleID))
        {
            telemetry.Context.GlobalProperties["ModuleId"] = moduleID;
        }
        // Add module name if available
        var moduleName = ConfigurationManager.AppSettings["ModuleName"];
        if (!string.IsNullOrEmpty(moduleName))
        {
            telemetry.Context.GlobalProperties["ModuleName"] = moduleName;
        }

        // Add trace ID if available
        var traceId = System.Diagnostics.Trace.CorrelationManager.ActivityId;
        if (traceId != Guid.Empty)
        {
            telemetry.Context.GlobalProperties["TraceId"] = traceId.ToString();
        }

        telemetry.Context.GlobalProperties["MachineName"] = Environment.MachineName.ToString();
    }
}
15
  • Are you running the app locally? Commented Apr 7 at 10:53
  • yes. in my PC. This code used to work earlier. maybe they have changed something Commented Apr 7 at 11:09
  • called the IngestionEndpoint via powershell , Using Azure CLI/Powershell ? If possible, can you please deploy, run the app and check once. Commented Apr 7 at 11:11
  • I used powershell. its not possible to deploy the app at the moment. I dont have permission. Is there anything you could think of that im doing wrong? Commented Apr 7 at 11:15
  • How have you configured Application Insights ? Manually or from Connected Services? Commented Apr 7 at 11:18

2 Answers 2

0

Need to have Tls12 in order to communicate with the ingestion end point. After setting this it worked

  System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 
Sign up to request clarification or add additional context in comments.

Comments

0

@Wathma Rathnayake, In addition to your solution please check the below points.

I am able to see the traces under "Exceptions" in Application Insights after using the custom error handler with ILogger.

enter image description here

enter image description here

I have configured Application insights from Connected Services, it has created a default ApplicationInsights.config file.

enter image description here

My Installed packages:

  <package id="log4net" version="2.0.15" targetFramework="net48" />
  <package id="Microsoft.ApplicationInsights" version="2.23.0" targetFramework="net48" />
  <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.4.0" targetFramework="net48" />
  <package id="Microsoft.ApplicationInsights.DependencyCollector" version="2.22.0" targetFramework="net48" />
  <package id="Microsoft.ApplicationInsights.PerfCounterCollector" version="2.22.0" targetFramework="net48" />
  <package id="Microsoft.ApplicationInsights.Web" version="2.22.0" targetFramework="net48" />
  <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.22.0" targetFramework="net48" />
  <package id="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" version="2.22.0" targetFramework="net48" />
  <package id="Microsoft.AspNet.FriendlyUrls" version="1.0.2" targetFramework="net48" />
  <package id="Microsoft.AspNet.FriendlyUrls.Core" version="1.0.2" targetFramework="net48" />
  <package id="Microsoft.AspNet.TelemetryCorrelation" version="1.0.8" targetFramework="net48" />
  <package id="Microsoft.Configuration.ConfigurationBuilders.Base" version="3.0.0" targetFramework="net48" />
  <package id="Microsoft.Configuration.ConfigurationBuilders.UserSecrets" version="3.0.0" targetFramework="net48" />
  <package id="Microsoft.Extensions.Configuration" version="2.2.0" targetFramework="net48" />
  <package id="Microsoft.Extensions.Configuration.Abstractions" version="2.2.0" targetFramework="net48" />
  <package id="Microsoft.Extensions.Configuration.Binder" version="2.2.4" targetFramework="net48" />
  <package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="2.2.0" targetFramework="net48" />
  <package id="Microsoft.Extensions.Logging" version="2.2.0" targetFramework="net48" />
  <package id="Microsoft.Extensions.Logging.Abstractions" version="2.2.0" targetFramework="net48" />
  <package id="Microsoft.Extensions.Logging.ApplicationInsights" version="2.23.0" targetFramework="net48" />
  <package id="Microsoft.Extensions.Logging.Log4Net.AspNetCore" version="8.0.0" targetFramework="net48" />
  <package id="Microsoft.Extensions.Options" version="2.2.0" targetFramework="net48" />
  <package id="Microsoft.Extensions.Primitives" version="2.2.0" targetFramework="net48" />

Yes, even I checked for the deployed app, the TLS version is set to 1.2.

enter image description here

Additionally, to ensure Telemetry is flushed without any crash, make sure to add the below line of code.

 _telemetryConfiguration.TelemetryChannel.Flush();

Code works when Instrument Key is used instead of Connection String. When used Instrument Key, Ingestion End point is directed to dc.services.visualstudio.com

This type of behavior is mostly seen when any older versions of NuGet packages are installed. Make sure to upgrade all the packages related to Application Insights to the latest version.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.