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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With