Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

C# Application Insights Errors are Logged as Traces – How do I log them as Exceptions?

$
0
0

So when I log to Application Insights, I first follow this guide to set up Application Insights AND File logging:

C# Log to Application Insights and File from your .NET 6 Application

To create a log statement, I can now use the ILogger interface, and log my exceptions:

public class MyClass
{
    private ILogger<MyClass> _logger;

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

    public void MyMethod()
    {
        try
        {
            // some code goes here
        }
        catch (Exception ex)
        {
            _logger.LogError("Failed to process message GUID: {exception}", message, ex)
        }
    }
}

The logging is this line:

_logger.LogError("some error message goes here");

But hey? My error message is logged as a Trace in Application Insights:

The exception is being logged as a Trace with the severity level "Error".
The exception is being logged as a Trace with the severity level “Error”.

SO WHAT IF I WOULD LIKE TO LOG THIS AS AN EXCEPTION?

To log errors as exceptions, add the exception as the first parameter of the call:

public void MyMethod()
{       
    try
    {
        // some code goes here
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Failed to process message GUID: {exception}", message, ex)
    }
}

Notice the “ex” as the first parameter for LogError()? This will now log the error as an exception:

Using the exception as the first parameter will log any errors as exceptions
Using the exception as the first parameter will log any errors as exceptions

If you don’t have an exception, you can call the method with an empty exception:

// Calling with an empty exception. This will leave an empty exception line in 
// Application Insights:
_logger.LogError(new Exception(), "ExecuteAsync failed");

// So you should add a text to the exception.
// You can also use an exception of a different type
// if you wish:
_logger.LogError(new InvalidOperationException("Invalid operation"), "ExecuteAsync failed");

// You can still use custom properties in the following text:
_logger.LogError(new InvalidOperationException("Invalid operation"), "ExecuteAsync failed: {ErrorCode}", 404);

SIDE NOTE: WHAT IS THE DIFFERENCE BETWEEN AN ERROR AND AN EXCEPTION?

There are many thoughts on the difference between an error and an exception. But when it comes to Application Insights, traces with severity level “Error” will be part of your trace stack. If your log lines have a shared operation ID, you can click on any message and see all messages from the same operation ID:

The trace with severity level: Error is part of the same operation.
The trace with severity level: Error is part of the same operation.

If you click an exception, however, only the exception is shown:

When clicking exceptions, the trace stack is not shown
When clicking exceptions, the trace stack is not shown

You will need to click the tiny trace stack button to see the relation between the exception and the trace stack:

The exception is part of the trace stack, but only after clicking the tiny stack button previously
The exception is part of the trace stack, but only after clicking the tiny stack button previously

SO WHAT DO I DO? DO I USE Trace OR Exception THEN?

This is where it gets opinionated. In my opinion, you either use Traces for your entire application, or you use exceptions for your entire application. Looking for errors 2 places can be confusing. I see one exception to this rule:

Let’s say that you have an application that reads an event from a datasource like a queue or a database. If the connection to this datasource fails, you could argue that this is so severe, that the application cannot continue, and should throw an exception. If the processing of the message fails because of a business rule failing, you should throw a Trace with severity level “error”.

But it’s up to you. Anyway, you are now an Application Insights Expert. Happy coding.

MORE TO READ:


Viewing all articles
Browse latest Browse all 285

Trending Articles