The Analogy: The Flight Recorder
When an aircraft has a bad day, nobody investigates by asking the pilot to remember harder. They pull the flight recorder: altitude, airspeed, control inputs, cockpit audio, all timestamped, all captured while things were going wrong. The recorder does not prevent accidents. It makes them explicable, which is what stops the next one.
Most bug reports arrive as the opposite of a flight recorder. "It crashed." "It didn't save." "There was an error." One sentence of hearsay about an event nobody watched, on a machine you cannot touch, in a state you cannot reproduce. Everything you do while writing the code decides whether that ticket takes five minutes or five days.
C# gives you the whole recorder: a stack trace that names the exact line, exception chains that keep the original cause, log entries with structure a machine can query, caller-info attributes the compiler fills in for free, and command-line tools that can attach to a running process and dump its memory. This lesson is about laying that instrumentation down deliberately, before the crash, so that when a failure does happen it arrives already explained.
Syntax or Core Structure
Three ingredients cover most of what you need: caller information injected at compile time, the exception chain walked in full, and a Stopwatch for anything you suspect is slow.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
Log("starting up");
try
{
Outer();
}
catch (InvalidOperationException ex)
{
Log("import failed: " + ex.Message);
Describe(ex);
}
var clock = Stopwatch.StartNew();
int total = 0;
for (int i = 0; i < 10_000; i++) total += i;
clock.Stop();
Log("summed to " + total + "; under a second: " + (clock.Elapsed.TotalSeconds < 1));
}
static void Outer()
{
try
{
Inner();
}
catch (FormatException inner)
{
// Add context at the layer boundary, keep the cause underneath.
throw new InvalidOperationException("row 3 could not be read", inner);
}
}
static void Inner() => int.Parse("not a number");
// [CallerMemberName] is filled in by the COMPILER at each call site,
// so the log knows where it came from without a string literal.
static void Log(string message, [CallerMemberName] string member = "")
=> Console.WriteLine($"[{member}] {message}");
// Walk the whole chain: the outermost exception is rarely the cause.
static void Describe(Exception ex)
{
int depth = 0;
for (Exception? e = ex; e is not null; e = e.InnerException, depth++)
Console.WriteLine(new string(' ', depth * 2) + "-> " + e.GetType().Name);
}
}
Output:
[Main] starting up
[Main] import failed: row 3 could not be read
-> InvalidOperationException
-> FormatException
[Main] summed to 49995000; under a second: True
The indented FormatException is the whole point. The exception that reached the handler said "row 3 could not be read", which is what a user needs; the exception underneath it says the row was unparseable text rather than a missing file, which is what a developer needs. Both survived, because Outer passed inner to the constructor instead of throwing a fresh exception with a friendlier message.
Technical Depth: Reading a Stack Trace Properly
A .NET stack trace is printed innermost frame first. The top line is where the exception was thrown; each line below it is the method that called the one above. Read it top-down to find the failure and bottom-up to find out why that code was running at all.
System.FormatException: The input string 'not a number' was not in a correct format.
at System.Number.ThrowFormatException[TChar](ReadOnlySpan`1 value)
at System.Int32.Parse(String s)
at Importer.ParseRow(String text) in C:\src\Importer.cs:line 42
at Importer.Run(String path) in C:\src\Importer.cs:line 17
The two frames that matter are the ones with your file and line numbers. Frames inside System.* tell you which framework call refused the input, not where the bug is. Those in file:line suffixes only appear when the matching .pdb symbol file shipped alongside the assembly — a Release build without symbols gives you method names and nothing else, which is why DebugType=portable symbols are worth publishing even for production.
| Member | Contains | Use for |
|---|---|---|
ex.Message | One human sentence | Showing a user, never for logic |
ex.StackTrace | The frame list as text | Finding the throwing line |
ex.InnerException | The wrapped cause, or null | Walking down to the real failure |
ex.GetType().Name | The exception type | Grouping alerts, dashboards |
ex.ToString() | Type + message + trace + inner chain | Logging - this is the one |
ex.Data | Loose key/value breadcrumbs | Extra context you attached |
Log ex.ToString() or hand the exception object itself to a logger. Logging ex.Message alone is the most common way teams end up with a log full of "Object reference not set to an instance of an object" and no idea which object.
Structured logging beats string concatenation
Microsoft.Extensions.Logging takes a message template plus values, not a finished sentence:
// Good: the file name is a queryable field called File.
logger.LogError(ex, "Import of {File} failed after {RowCount} rows", path, rows);
// Bad: one opaque string; nothing to filter or aggregate on.
logger.LogError($"Import of {path} failed after {rows} rows: {ex}");
The first form lets a log system answer "show me every failure for invoices.csv" without regular expressions, and it skips formatting entirely when the level is disabled. The interpolated form builds the string whether or not anyone will read it, and throws the structure away. It also loses the exception: passing ex as the first argument is what attaches the type, trace and inner chain as separate fields.
Assertions and trace calls that cost nothing in production
Debug.Assert(condition, message) and Debug.WriteLine are annotated [Conditional("DEBUG")], which means the compiler removes the call sites from a Release build. They are free in production and loud in development — the right place for invariants you believe can never be false:
Debug.Assert(total >= 0, "totals cannot go negative"); // gone in Release
Trace.WriteLine("cache miss for " + key); // survives Release
Trace is the sibling that stays. Use Debug for things only a developer should see, Trace (or better, ILogger) for anything you might want on a live machine.
Catch nothing in the middle, everything at the edge
Every long-running program needs a handler at each boundary — the place where losing the current unit of work is acceptable but losing the process is not:
| Boundary | Hook |
|---|---|
| Whole process, last resort | AppDomain.CurrentDomain.UnhandledException |
A Task nobody awaited | TaskScheduler.UnobservedTaskException |
| One HTTP request | app.UseExceptionHandler(...) middleware |
| One message or job | try/catch around the single item |
| A background timer tick | try/catch inside the callback |
The process-level hooks are for recording, not recovery: by the time UnhandledException fires, the runtime is already shutting down.
Correlation: one id through the whole story
A single user action can touch four services and produce forty log lines. System.Diagnostics.Activity carries an id across those hops automatically, and ASP.NET Core starts one per request:
logger.LogInformation("Charging card for {OrderId} (trace {TraceId})",
orderId, Activity.Current?.TraceId.ToString() ?? "none");
Stamp that trace id onto every log line and onto the error page the user sees. When they quote it back to support, you can pull the exact forty lines instead of guessing from timestamps.
Tools for a process that is already misbehaving
Attach to a live process from the command line; none of these require a debugger or a restart:
| Tool | Answers |
|---|---|
dotnet-counters | Is it allocating, throwing, or queueing right now? |
dotnet-trace | Which methods are hot over the next 30 seconds? |
dotnet-dump | What is on the heap at this instant? |
dotnet-gcdump | What is holding memory that should be free? |
dotnet-stack | What is every thread doing? |
And for timing, always Stopwatch rather than subtracting DateTime.Now values: Stopwatch uses a monotonic high-resolution counter, so an NTP correction or a daylight-saving jump cannot make an operation appear to take minus one hour.
Real World Example: A Worker That Explains Its Failures
A background worker takes jobs off a queue. One bad job must not stop the worker, every outcome must be logged at the right level, and a failure must name both the job and the underlying cause.
using System;
record Job(string Id, string Payload);
class JobFailedException : Exception
{
public JobFailedException(string jobId, string message, Exception inner)
: base(message, inner) => JobId = jobId;
public string JobId { get; }
}
class Program
{
static void Main()
{
Job[] jobs =
{
new Job("job-1", "42"),
new Job("job-2", "seven"),
new Job("job-3", "0"),
new Job("job-4", "8")
};
int done = 0;
foreach (Job job in jobs)
{
// The boundary is one job: a bad payload costs one job, not the worker.
try
{
Run(job);
done++;
Write("info", job.Id, "completed");
}
catch (JobFailedException ex)
{
Write("error", ex.JobId, ex.Message + " | cause " + Chain(ex));
}
}
Write("info", "worker", done + "/" + jobs.Length + " jobs completed");
}
static void Run(Job job)
{
try
{
int value = int.Parse(job.Payload);
Write("debug", job.Id, "result " + (100 / value));
}
catch (Exception inner) when (inner is FormatException or DivideByZeroException)
{
throw new JobFailedException(job.Id, "payload '" + job.Payload + "' rejected", inner);
}
}
static string Chain(Exception ex)
{
var parts = new System.Collections.Generic.List<string>();
for (Exception? e = ex; e is not null; e = e.InnerException)
parts.Add(e.GetType().Name);
return string.Join(" <- ", parts);
}
static void Write(string level, string scope, string message)
=> Console.WriteLine($"{level,-5} [{scope}] {message}");
}
Output:
debug [job-1] result 2
info [job-1] completed
error [job-2] payload 'seven' rejected | cause JobFailedException <- FormatException
error [job-3] payload '0' rejected | cause JobFailedException <- DivideByZeroException
debug [job-4] result 12
info [job-4] completed
info [worker] 2/4 jobs completed
Two failures, two different underlying causes, and the log distinguishes them without anyone reading English. job-2 was bad data; job-3 was a division the code should have guarded. A real logger would replace Write with logger.LogError(ex, "Job {JobId} rejected payload {Payload}", ...), and the string in the middle would become two queryable fields — but the shape of the diagnosis is exactly this: level, scope, what happened, what caused it.
Common Mistakes
- Logging
ex.Messageonly. One sentence with no type, no line and no inner exception. Log the exception object (orex.ToString()) so the whole chain lands in the record. throw ex;in the handler. It resets the stack trace to that line, destroying the location you were trying to record. Usethrow;to rethrow, or wrap with an inner exception.- Swallowing with an empty
catch.catch { }produces the worst possible bug report: nothing happened, and nothing was written down. - Interpolating log messages.
logger.LogInformation($"user {id} saved")formats eagerly and destroys the{UserId}field a log system could have filtered on. - Publishing without symbols. No
.pdb, no line numbers, and every trace ends at a method name. Portable PDBs are small; publish them. - Timing with
DateTime.Now. It is low-resolution and it can move backwards when the clock is corrected.Stopwatchis monotonic and cheap. - Logging the same failure at every level. A
catch-log-rethrow at four layers turns one incident into four alerts. Log once, where the outcome is decided. - Relying on
Debug.WriteLinein production. Those calls are compiled out of Release builds; if you need the line on a live machine, it has to beILoggerorTrace.
Best Practices
- Log the exception object, at the boundary that decides the outcome, exactly once.
- Use message templates with named placeholders so fields stay queryable, and pass the exception as the first argument.
- Wrap failures at layer boundaries with an inner exception so both the friendly explanation and the technical cause survive.
- Put a
try/catcharound each unit of work in any long-running loop, plus a process-level hook purely for recording. - Stamp a correlation or trace id on every line and show it to the user on the error page.
- Use
[CallerMemberName]andnameofinstead of hand-written literals that drift when code is renamed. - Keep
Debug.Assertfor invariants you believe are impossible, and let it vanish in Release. - Measure with
Stopwatch, and publish portable PDBs so the traces you collect have line numbers.
Practice Exercises
- Read the trace. Write a three-method chain (
MaincallsLoadcallsParse) whereParsethrows. Printex.ToString()and identify, line by line, which frames are yours and which belong to the framework. Then delete the.pdbfrombinand note exactly what disappears from the output. - Walk the chain. Write
string Explain(Exception ex)that returns every exception in the chain asType: messagejoined by<-, then throw a three-deep nest (IOExceptioninsideFormatExceptioninsideInvalidOperationException) and print the result. - Caller info. Write
void Check(bool condition, string description, [CallerMemberName] string member = "", [CallerLineNumber] int line = 0)that prints a failure with the calling method and line. Call it from two different methods and confirm the values change without you passing anything. - Boundary handler. Write a loop over ten jobs where job 4 throws. Handle it so the loop finishes all ten, records the failure with the job number, and prints a final summary line — then move the
tryoutside the loop and describe what the log loses.