Letβs go through debugging and logging in C# β essential tools for finding and fixing issues and monitoring application behavior.
π 1. Debugging in C#
Debugging is the process of examining your code while it runs to identify and fix errors.
Common Techniques
-
Breakpoints
-
Set in Visual Studio or VS Code to pause execution at a specific line.
-
Allows you to inspect variables, watch expressions, and step through code.
-
-
Step Execution
-
Step Into (F11)
β enter a method call -
Step Over (F10)
β execute the method without entering it -
Step Out (Shift+F11)
β exit current method
-
-
Watch & Immediate Window
- Monitor variables and evaluate expressions during debugging.
-
Conditional Breakpoints
-
Break only when a condition is true:
// Example: break when i == 5 if(i == 5) { /* breakpoint here */ }
-
π 2. Logging in C#
Logging is recording information about your applicationβs execution to help debug, monitor, or audit behavior.
Using Console.WriteLine
(Simple Logging)
int x = 5;
Console.WriteLine($"Value of x: {x}");
- Quick and easy for small apps or testing, but not ideal for production
Using System.Diagnostics.Debug
using System.Diagnostics;
Debug.WriteLine("This is a debug message");
Debug.WriteLine($"Variable value: {x}");
-
Outputs messages to Output window in Visual Studio
-
Only visible in Debug builds, not Release
Using ILogger
and Logging Frameworks
-
ASP.NET Core provides built-in logging via
ILogger
-
Supports multiple targets: console, files, databases, etc.
using Microsoft.Extensions.Logging;
public class Program
{
private readonly ILogger<Program> _logger;
public Program(ILogger<Program> logger)
{
_logger = logger;
}
public void Run()
{
_logger.LogInformation("Application started");
_logger.LogWarning("This is a warning");
_logger.LogError("An error occurred");
}
}
Popular Logging Libraries
Library | Description |
---|---|
NLog | Flexible, multiple targets |
Serilog | Structured logging, JSON output |
log4net | Classic logging framework |
- These libraries allow file logging, rolling logs, and structured logging
π 3. Best Practices
-
Use proper log levels:
Debug
,Info
,Warning
,Error
,Critical
-
Avoid excessive logging in performance-critical code
-
Include context: timestamps, user ID, method names
-
Separate Debug and Production logging
-
Dispose or close loggers properly if writing to files
π 4. Summary Table
Feature | Description |
---|---|
Breakpoints | Pause execution to inspect code |
Step Execution | Navigate through code line by line |
Debug.WriteLine | Quick debug messages in development |
Console.WriteLine | Simple logging to console |
ILogger / NLog / Serilog | Structured, production-ready logging |
Best Practices | Proper log levels, context, avoid performance hits |
β Tip:
-
Combine debugging for immediate problem solving and logging for long-term monitoring.
-
Structured logging (with Serilog or NLog) is preferred for production apps.