ILogger Best Practices in .NET: Structured Logging That Helps You Debug (video)

Practical ILogger best practices for .NET: message templates instead of string interpolation, logging exceptions correctly, log levels, scopes, LoggerMessage source generators, and what never to log.

Read the full article

Transcript

ILogger Best Practices in .NET: Structured Logging That Helps You Debug. Here's the short version.

Most production incidents are debugged from logs, and most logs are written in a hurry. ILogger in .NET supports structured logging out of the box, but only if you use it the way it was designed.

Use message templates, not string interpolation. ILogger message templates keep each value as a named property that log tools like Seq, Elasticsearch, Application Insights. String interpolation flattens everything into one string and builds it even when the level is disabled.

Here's the problem in code: one flat string, built on every call.

And here's the fix: OrderId and CustomerId become searchable fields.

Pass the exception as the first argument. LogError(ex, "...") keeps the exception type, message, and full stack trace. Logging only ex.Message throws away the stack trace, which is the part you need.

Use the LoggerMessage source generator on hot paths. For code that logs thousands of times a second.

Want to find these issues in your own code? Connect your GitHub repository to CodeInspector. You'll get findings with the file, line, severity, and a recommended fix, plus HTML and PDF reports for your team. Start free at codeinspector.app.

More videos

All videos