Logs Not Visible in Application Insights for .NET Framework 4.6.1 Console App

sonal khatri 51 Reputation points
2024-06-05T07:03:36.05+00:00

Hi,

I have a console app in .NET Framework 4.6.1 and I am trying to add Application Insights logging, but the logs are not visible in Application Insights. What am I doing wrong?

My code:

public class Program
{
    private static readonly ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
    {
        builder.AddConsole();
        builder.AddApplicationInsights("instrumentationKey");     });

    private static readonly ILogger<Program> logger = loggerFactory.CreateLogger<Program>();
    private static readonly ILogger<Patient> patientLogger = loggerFactory.CreateLogger<Patient>();

    public static void Main(string[] args)
    {
        logger.LogInformation("Test Main");
        Program p = new Program();
        p.OnStart();
    }

    protected void OnStart()
    {
        CallService();
    }

    public void CallService()
    {
        try
        {
            Patient patient = new Patient(patientLogger);
            patient.Check();

        }
        catch (Exception ex)
        {
            logger.LogError(ex, "An error occurred while calling the service.");
        }
    }
}

public class Patient
{
    private readonly ILogger<Patient> _logger;

    public Patient(ILogger<Patient> logger)
    {
        _logger = logger;
    }

    public void Check()
    {
        _logger.LogInformation("Checking patient...");

    }
}

Azure Monitor
Azure Monitor
An Azure service that is used to collect, analyze, and act on telemetry data from Azure and on-premises environments.
3,037 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,649 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,408 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Deepanshukatara-6769 8,060 Reputation points
    2024-06-05T07:44:38.07+00:00

    Hi Sonal . Welcome to MS Q&A

    To add Application Insights logging to console applications, first install the following NuGet packages:

    The following example uses the Microsoft.Extensions.Logging.ApplicationInsights package and demonstrates the default behavior for a console application. The Microsoft.Extensions.Logging.ApplicationInsights package should be used in a console application or whenever you want a bare minimum implementation of Application Insights without the full feature set such as metrics, distributed tracing, sampling, and telemetry initializers.

    using Microsoft.ApplicationInsights.Channel;
    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Logging.ApplicationInsights;
    using System;
    using System.Threading.Tasks;
    
    namespace ConsoleApp
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                using var channel = new InMemoryChannel();
    
                try
                {
                    IServiceCollection services = new ServiceCollection();
                    services.Configure<TelemetryConfiguration>(config => config.TelemetryChannel = channel);
                    services.AddLogging(builder =>
                    {
                        // Only Application Insights is registered as a logger provider
                        builder.AddApplicationInsights(
                            configureTelemetryConfiguration: (config) => config.ConnectionString = "<YourConnectionString>",
                            configureApplicationInsightsLoggerOptions: (options) => { }
                        );
                    });
    
                    IServiceProvider serviceProvider = services.BuildServiceProvider();
                    ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();
    
                    logger.LogInformation("Logger is working...");
                }
                finally
                {
                    // Explicitly call Flush() followed by Delay, as required in console apps.
                    // This ensures that even if the application terminates, telemetry is sent to the back end.
                    channel.Flush();
    
                    await Task.Delay(TimeSpan.FromMilliseconds(1000));
                }
            }
        }
    }
    
    

    Please check this doc which include step by step process -->https://learn.microsoft.com/en-us/azure/azure-monitor/app/ilogger?tabs=dotnet5

    Kindly accept answer if it helps , please let me know if any questions

    Thanks

    Deepanshu