Guide | .Net

How to Handle Exceptions in .NET

How to Handle Exceptions in .NET

Where are .NET Errors Logged?

Although every developer aims for bug-free code, it’s nearly impossible to deploy an application without a few unwanted bugs. You can test an application thoroughly, but still have logic errors. These errors can vary from critical issues that inhibit proper use of the application to minor annoyances. Regardless, you must be able to fix any bug in the application before it becomes a huge nuisance for your users. You detect bugs and find the .NET object that’s causing it by using logging techniques.

.NET can log errors to the Windows Event Viewer, a database, or a file using libraries already included in the .NET framework. Each solution has its pros and cons. You can use your own custom libraries or simplify the process using third-party libraries installed from NuGet. .NET is a backend coding platform as opposed to client-side languages such as JavaScript. This means that your logging solution for .NET must be able to integrate with your application and your server. If the application is public, the logging solution must also be secure; otherwise, attackers can gain valuable insight on critical components for malicious purposes.

Types of logs

Logging provides root cause analysis for more than just .NET applications. The operating system, system applications such as IIS, and security and network appliances log events to some location determined by the administrator configurations. Custom applications may have no logging components at all, but the operating system or host application such as IIS will log errors. For instance, if your web-based application has an unhandled error, IIS might log a 500 server error. This error value is displayed in the user’s browser, but developers can use internal logs to find the root cause of the bug.

Finding the root cause of a general 500 server error is much more difficult than logging the event using custom error handling, so the developer should always take time to create their own application logs either through third-party tools or by direct logging to Event Viewer files, plain-text files, or a database.

Some examples of logs usually stored in a system include:

  • Security logs: security events from intrusion detection or common attacks either within the network or from public-facing appliances.

  • Application logs: logs specific to an application. These can be custom logs created by the application developers or third-party tools.

  • Operating system logs: logs specific to the operating system on the local machine.

  • IIS logs: .NET apps usually run on IIS servers, and the hosting application uses its own logs to track events with installed websites. Note: .NET applications can also run on Linux using Mono.

  • Network logs: most network appliances, servers, and hardware have configurations that allow for logging events.

Log levels

Before you log errors, you should know the various log levels. In .NET, log levels are stored as an Enum data type available from the Microsoft.Extensions.Logging namespace. These log levels define the seriousness of the event. For instance, an "Information" log level might not need any code corrections, but a critical error needs immediate attention.

The following are the log levels stored in the LogLevel Enum:

  • None (6): Not used for writing log messages. Specifies that a logging category should not write any messages.

  • Critical (5): Critical failures that describe unrecoverable application or system crashes. Requires immediate attention.

  • Error (4): Failure of a specific flow of execution that stopped due to an error. Failure is localized to a specific function rather than an application-wide crash.

  • Warning (3): An unexpected or abnormal event that does not cause interruption of application execution.

  • Information (2): Informational messages that can help indicate the flow of operation of an application.

  • Debug (1): Debugging information normally logged just for development. These logs should be removed for production.

  • Trace (0): Logs that contain critical detail about an application’s workflow. They can contain sensitive information, so they should never be turned on in production.

Default logs in Event Viewer

If you’ve worked with server applications, you know that they record errors to Event Viewer where you can review them while you’re debugging. Windows groups events into categories; by default, an IIS or desktop application logs events to the "Application" category.

Screenshot of Event Viewer window with an error log level event shown

In the image above, an error is highlighted among several "Information" events. Event Viewer gives you a way to check for application errors, but you must know what to look for. The section underneath the list of events is where you can view details. Notice that the log level is also displayed. The details section gives you a better explanation of why the error was triggered.

Unfortunately, the Event Viewer has no search features or graphing tools. There is no way to search for specific error codes. You can scroll through events until you find the right one, but you might have thousands of events that interfere with your ability to drill down and find the ones that you need for any specific issue.

Without any error handling, an event logged to Event Viewer means that your application failed. When an application fails, it crashes — it’s not enough to have logging. You also need to properly handle errors so the user doesn’t get a confusing error message and then a crashed application. If that happens, the user’s work is no longer saved. Frustrated users will choose another application that’s more stable. Error handling ensures that your application either continues after the error or closes gracefully, saving the user’s data. Several third-party tools are available that will help you log to the Event Viewer, but you can store logs in additional locations.

The two other popular logging locations are a database already used by the application or a local file. These two options come with their own set of difficulties. With a database, you need a database connection and server that can handle the resources needed for database activity. Usually, this means that you need a separate server in addition to your hosting server. Log files are easier to set up: You can store them on the local server, but then you have the security overhead costs of protecting these files from public access.

Logging in web versus desktop versus mobile

.NET can be used for web, desktop, and mobile applications. .NET has gone through several changes over the years, and the operating system you target will determine the type of application you create. When it comes to logging, however, you can log your events regardless of the platform the application is hosted on.

The syntax used in web, desktop, or mobile is similar, and if you use a third-party solution the code will be the same throughout each platform code base. With logging, each device or server has its own native logging solution. With web applications, you log to the server’s event logs. With desktop software, you log to event logs on the local machine. With Xamarin, you log to the device logging solution — NSLog for iOS and android.util.Log for Android are the most common.

Logging to console in Visual Studio

While developers program an application, the console is the most common place to review errors.. Developers write to the console to see run-time errors. It’s a convenient way to begin development when you first start an application and you need a quick and easy way to see minor errors. .NET’s framework has a Write.Console() method that writes to the command console. You can use this with a desktop application as you capture exceptions. The following example is a public LogError method that captures an exception and logs it to the console.

private void LogError( string message)
{

    string source;
    string log;
    source = "RollbarDotNetGuide";
    Console.Write(source + " error: " + message);

}

An alternative to the Console.Write method is the Console.WriteLine method. This method works in the same way, but it automatically adds a new line character to the end of the message, so each of your statements print to a new line in the console.

Logging to Event Viewer for web or desktop applications

When users run a compiled and released Windows app, there is no console to view the logs. Instead, Windows offers a standard place to store log messages called the Windows Event Log. You can view these events with the Event Viewer.

private void LogError( string message)
{

    string source;
    string log;

    source = "RollbarDotNetGuide";
    log = "Application";

    if (!EventLog.SourceExists(source))
    EventLog.CreateEventSource(source, log);

    EventLog.WriteEntry(source, message);
    EventLog.WriteEntry(source, message, EventLogEntryType.Error);

}

In the code above, a LogError method takes an error message and adds it to Event Viewer logs.

Android and iOS mobile devices

With Android development (using Xamarin), the simplest solution is to override the Write and WriteLine methods available in .NET. Normally, these two methods are used during development to view output while running the application in debug mode, but they can be overridden to write to the Android Device Monitor.

public class LogTraceListener : System.Diagnostics.TraceListener
{
    public override void Write(string message)
    {
        Android.Util.Log.WriteLine(Android.Util.LogPriority.Debug, "Android App", message);
    }

    public override void WriteLine(string message)
    {
        Android.Util.Log.WriteLine(Android.Util.LogPriority.Debug, "Android App", message);
    }
}

Logging libraries like Nlog

A logging library provides a standard interface regardless of which type of application you are writing. It provides you pluggable and flexible output options including file, event log, or even remote log management solutions. One of the most popular logging libraries for .NET is Nlog. After you add the NLog library to your project, you need to instantiate the class and log your events based on the error level.

Logger logger = LogManager.GetLogger("console");
logger.Trace("My trace message");
logger.Debug("Debug message");
logger.Info("Information message");

NLog can be used for all .NET solutions including MVC, Universal Windows Platform (UWP), Core, and Xamarin applications. However, a logging library is not a complete solution. Any local logging solution suffers the same disadvantages as the Event Viewer. A lack of monitoring, alerts, and aggregation features makes them just as difficult to get high-level visibility, and they may lack the debug-level data needed for root cause analysis.

Error monitoring, not just logs

At the surface, it looks like creating logs from your application is enough, but logging without any kind of monitoring leaves you blind to what is going on under the hood. Suppose you have an issue with your application in which users are unable to finalize a purchase. You’re logging an event that explains the error to developers, but no one is aware of the issue in real time and your customers continue to have checkout issues. It isn’t until a customer complains that developers are finally aware, but this can be after thousands of dollars are lost.

Monitoring combined with logging gives administrators and developers immediate attention to a problem and helps them find it more quickly. Debugging involves research and analysis, so even just a line in a log file might not be enough for a developer to understand the problem. More research into previous events might be needed, so the ability to search logs is also necessary. Your logs could be thousands of line items, so the ability to search makes debugging and root cause analysis much faster and more efficient.

Rollbar gives you the ability to log, monitor, search, and find errors and their underlying issues using a customized event viewer. Using a brand new account, we logged the first error in Rollbar when a .NET method threw a DivideByZero exception.

Screenshot of Rollbar dashboar

In the example above, you can see that the latest error was logged to Rollbar. Should you have any bugs in your application, the Rollbar dashboard gives you a quick view of the latest events so you can review your code and determine their location. The message shown in the "Title" column is the custom message configured in code. It’s important to create messages that help developers find errors quickly.

With Rollbar, you can view and analyze errors from a browser application. It has several features for .NET that make debugging more efficient including local variables, request parameters, and suspected deployments. It’s as easy as other solutions to install: just configure the application to work with Rollbar’s .NET SDK.