Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Microsoft.Extensions.Logging with Application Insights to log events and metrics

The ILogger interface has just one Log method:

void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter);

Application insights gives me a rich api like this:

TrackMetric(string name, double value, IDictionary<string, string> properties = null);
TrackException(Exception exception, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null);
TrackTrace(string message, SeverityLevel severityLevel, IDictionary<string, string> properties);

How should I implement a custom ILogger and still have all the features of application insights? One way I can think of is to define different TState types like below:

class Trace
{
    public string Message {get;set;};
    public IDictionary<string, string> Properties;

    public Trace(string message, IDictionary<string, string> properties)
    {
        this.Message = message;
        this.Properties = properties;
    }    
}

then when I need to trace, I do something like:

logger.Log<Trace>(LogLevel.Information, eventId, new Trace("sample trace",null));

In this way I switch which trackXXX method I used in the Log<TState> implementation based on the type of TSTate (I create types for Exception, Metric and Event). But this looks too complicated to write a simple trace, any other ways I am missing?

like image 531
AzureMinotaur Avatar asked Nov 07 '22 23:11

AzureMinotaur


1 Answers

When you are using Application Insights SDK for ASP.NET Core and enable Application Insights, internal ILogger implementation is created. You can see here how it works.

So to answer your question, if you are using AI SDK for ASP.NET Core, you shouldn't need to implement your own ILogger. If you must however, you can use the linked implementation as example.

like image 142
Alex Bulankou Avatar answered Nov 14 '22 23:11

Alex Bulankou