Sanketh
Sanketh

Reputation: 79

Logging in Application Insights for .NET Core 2.1 Console app with LoggerFactory

I have a .NET Core 2.1 Console application. I have added all the Nuget packages needed.

private static IConfiguration Configuration { get; set; }
static void Main(string[] args)
{
    ServiceCollection services = new ServiceCollection();
    ConfigureServices(services);
    var serviceProvider = services.BuildServiceProvider();
    var logger = serviceProvider.GetService<ILoggerFactory>()
        .CreateLogger<Program>()
    var service = serviceProvider.GetService<TestClass>();
    service.TimmerTriggerTask();
}

private static void ConfigureServices(IServiceCollection services)
{
    IConfiguration config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", true, true)
            .Build();
    services.AddApplicationInsightsTelemetry("8028437c-1111-2222-8293-2cf3f3f106a8"); //instrumentation key
    services.AddLogging(builder => builder.AddConsole());
}

TestClass.cs
public class TestClass
{
    private readonly ILogger<TestClass> _logger;

    public TestClass(ILogger<TestClass> logger)
    {
        Console.WriteLine("Ctor");
        _logger = logger;
    }

    public void TimmerTriggerTask()
    {
        Console.WriteLine("Timer");
    //LOG BELOW IN APPLICATION INSIGHTS
        _logger.LogTrace("Hello World");
        _logger.LogInformation(DateTime.Now.ToString());
    }
}

I need to log all the information and exceptions in Application Insights. looking to integrate loggerfactory with applicationInsights.

I am looking for something what we can do in .NET Core Web app

WebHost.CreateDefaultBuilder(args).UseApplicationInsights()
loggerFactory.AddApplicationInsights(app.ApplicationServices, defaultLogLevel);

Please help me as how do i use logger classes to log into applicationinsights.

Please provide an alternative solution if what i am doing is incorrect.

Upvotes: 0

Views: 9905

Answers (3)

IBrown
IBrown

Reputation: 51

LoggerFactory.AddApplicationInsights has been deprecated. Add a reference to Microsoft.Extensions.Logging.ApplicationInsights and use the following code. You can find a full example from Microsoft here.

    static void Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();

        // Channel is explicitly configured to do flush on it later.
        var channel = new InMemoryChannel();
        services.Configure<TelemetryConfiguration>(
            (config) =>
            {
                config.TelemetryChannel = channel;
            }
        );

        services.AddLogging(builder =>
        {
            builder.AddConsole();
            builder.AddApplicationInsights("[AI Instrumentation Key here]");
        });

        var provider = services.BuildServiceProvider();
        var logger = provider.GetService<ILogger<Program>>();

        logger.LogInformation("This will show up in Application Insights"); 

        // Explicitly call Flush() followed by sleep is required in Console Apps.
        // This is to ensure that even if application terminates, telemetry is sent to the back-end.
        channel.Flush();
        Thread.Sleep(1000);
    }

You can add custom dimensions to implement structured logging by using log message templates.

public void DoTheThings()
{ 
    var id = 12345;
    var duration = 300;

    logger.LogInformation(
        "Did the things for Id: {actionId} in {durationMs}ms. Params: {p2}, {p1}", 
        id, duration, "param1", "param2");
}

This will produce a trace in Application Insights with the message:

"Did the things for Id: 12345 in 300ms.  Params: param1, param2"

and customDimensions including:

{ 
    "actionId": "12345",
    "durationMS": "300",
    "p2" : "param1",
    "p1" : "param2"
}

Notice that:

  1. The message template is not an interpolated string.
  2. The property name in customDimensions is based on the message template not the argument.
  3. The template properties are bound to arguments in sequence not by name.

Upvotes: 5

Ivan Glasenberg
Ivan Glasenberg

Reputation: 30025

update:

For .net core 2.1 console app, you can use the following code:

using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;

        static void Main(string[] args)
        {

            var telemetryClient = new TelemetryClient() { InstrumentationKey = "your instrumentation key" };

            ServiceCollection services = new ServiceCollection();
            services.AddSingleton(x => telemetryClient);

            var provider = services.BuildServiceProvider();

            var loggerFactory = new LoggerFactory();
            loggerFactory.AddApplicationInsights(provider, LogLevel.Information);

            var logger = loggerFactory.CreateLogger<Program>();
            logger.LogInformation("a test from 0911 again...");
            logger.LogError("a error test from 0911 again...");


            Console.WriteLine("aaa");

            telemetryClient.Flush();
            System.Threading.Thread.Sleep(5000);
        }

After running, in the visual studio output window, I can see the telemetry data are sent, screenshot as below: enter image description here

And also, it was also shown in azure portal, screenshot as below: enter image description here

Upvotes: 2

Hugo Quintela Ribeiro
Hugo Quintela Ribeiro

Reputation: 779

I had the same question some months ago and ended up building my own log provider that manages a TelemetryClient to send the log to AI.

Meanwhile I think that Microsoft has built a package exactly for that:

Check it out here: https://github.com/Microsoft/ApplicationInsights-aspnetcore.

Upvotes: 0

Related Questions