In this tutorial, we will explore the concept of exception logging and monitoring in C#. By logging exceptions, you can keep track of the errors that occur in your application and use this information for debugging and improvement.
You will learn:
NLog
Prerequisites:
In C#, exceptions are runtime errors that break the normal flow of execution. They are handled using try
, catch
, and finally
blocks.
try {
// code that may throw an exception
} catch (Exception ex) {
// handle the exception
} finally {
// code to be executed regardless of an exception
}
NLog is a flexible and easy-to-use logging platform for various .NET platforms, including .NET standard. It is one of the most popular frameworks for logging in .NET.
First, you need to install the NLog NuGet package. Go to Solution Explorer > Right Click on Project > Manage NuGet Packages > NLog
.
To use NLog for exception logging, you need to create a Logger instance and call the Error
method, passing the exception object and a custom message.
var logger = NLog.LogManager.GetCurrentClassLogger();
try {
// code that may throw an exception
} catch (Exception ex) {
logger.Error(ex, "An error occurred while processing your request.");
}
using System;
using NLog;
public class Program {
private static Logger logger = LogManager.GetCurrentClassLogger();
public static void Main() {
try {
int a = 10;
int b = 0;
Console.WriteLine(a / b);
} catch (Exception ex) {
logger.Error(ex, "An error occurred while dividing");
}
}
}
In this example, we deliberately cause a DivideByZeroException
by attempting to divide a number by zero. We then log the exception using NLog.
using System;
using NLog;
public class Program {
private static Logger logger = LogManager.GetCurrentClassLogger();
public static void Main() {
try {
int a = 10;
int b = 0;
Console.WriteLine(a / b);
} catch (Exception ex) {
logger.Error(ex, "An error occurred while dividing {a} by {b}", a, b);
}
}
}
Here, we extend the previous example by including additional data in the log message. When the exception is logged, the values of a
and b
are included in the message.
In this tutorial, we covered the fundamentals of exception handling in C# and how to log exceptions using the NLog library. We also looked at how to include additional data in log messages.
You should now be able to debug your application more effectively by logging and monitoring exceptions. Further, you can explore the NLog documentation to learn more about its features and capabilities.
Exercise 1:
Create a program that causes a NullReferenceException
and log the exception using NLog.
Exercise 2:
Extend the program from Exercise 1 by including additional data in the log message.
Solutions and explanations:
// Exercise 1
using System;
using NLog;
public class Program {
private static Logger logger = LogManager.GetCurrentClassLogger();
public static void Main() {
try {
string str = null;
Console.WriteLine(str.Length);
} catch (Exception ex) {
logger.Error(ex, "An error occurred while getting string length");
}
}
}
This program throws a NullReferenceException
because we are trying to access the Length
property of a null string. The exception is then logged using NLog.
// Exercise 2
using System;
using NLog;
public class Program {
private static Logger logger = LogManager.GetCurrentClassLogger();
public static void Main() {
try {
string str = null;
Console.WriteLine(str.Length);
} catch (Exception ex) {
logger.Error(ex, "An error occurred while getting length of {str}", str);
}
}
}
In this program, we are logging the exception along with the value of str
. Since str
is null, the log message will include that information.
These exercises should help you practice and reinforce what you've learned. Happy coding!