Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 52 ยท Dependency Injection, Configuration and Logging

Logging and Diagnostics

Use ILogger in ASP.NET Core: log levels, categories and filters, structured message templates, scopes, LoggerMessage and simple request logging.

When a web app misbehaves in production, you cannot attach a debugger and you cannot ask the user what happened. What you have is whatever the app wrote down. Logging is that written record, and in ASP.NET Core it is built in: every service can ask for an ILogger, every framework component writes to the same system, and you decide where the lines go and how loud they are.

This lesson covers the parts you use every day: log levels, categories and filtering, structured message templates, scopes, high-performance logging with LoggerMessage, and a small request-logging middleware. The general Microsoft.Extensions.Logging model is introduced in the C# lesson on logging; here we focus on how it behaves inside a web application and how to see it work. If dependency injection is new, read Dependency Injection in ASP.NET Core first.

How logging is wired

WebApplication.CreateBuilder() registers logging for you. Your code asks for ILogger<T>, where T is usually the class that is logging. The generic argument becomes the category: the full type name, such as MyShop.Checkout. Each log call has a level, a message and optional arguments. Before anything is written, the call passes through the configured filters, then reaches every registered provider (console, debug output, event log, or your own).

flowchart LR
    A["Your code<br/>ILogger of Checkout"] --> B["Filters<br/>category + level rules"]
    F["Framework code<br/>Microsoft.AspNetCore.*"] --> B
    B --> C["Console provider"]
    B --> D["Debug provider"]
    B --> E["Your own provider"]

Application and framework code share one pipeline; filters decide what reaches each provider.

The default providers in a new app write to the console. In the examples below we call ClearProviders() and add a tiny provider of our own that prints one predictable line per entry, so the output on this page is stable. The provider is plain boilerplate, and you can ignore its details for now.

Levels and categories

There are six levels, from most to least detailed:

Level Use it for
Trace Extremely detailed diagnostics; may contain sensitive data; off in production
Debug Information useful while developing or investigating
Information Normal, notable events: "order placed", "user signed in"
Warning Something unexpected happened, but the app continues
Error An operation failed (often with an exception)
Critical The app or machine is in serious trouble

A minimum level drops everything below it. You can set it for the whole app with SetMinimumLevel, and then override it for any category prefix with AddFilter. The longest matching prefix wins. That is how you keep your own Debug lines while silencing a chatty framework namespace.

C# Levels, categories and filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Four lines from Checkout appear (the trace line is below the minimum), and only the Error from Noisy.Cache. Inside a real app you configure the same thing in appsettings.json under "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, so you can raise or lower verbosity without recompiling (Configuration and the Options Pattern explains how that file is loaded).

A common production setup is Default: Information and Microsoft.AspNetCore: Warning. The framework's own Information messages are numerous, since every request produces a few of them, and they are rarely what you are looking for.

Structured logging: templates, not string building

The most important habit in .NET logging is this: write a message template with named placeholders and pass the values as arguments.

C#
// Good: structured. The template stays constant, the values are named properties.
log.LogInformation("Order {OrderId} placed by {Customer}", orderId, customer);

// Bad: the values are baked into one string before logging sees them.
log.LogInformation($"Order {orderId} placed by {customer}");

Both print nearly the same text on the console. The difference appears when your logs go to a system that understands structure (Seq, Elastic, Application Insights, OpenTelemetry collectors). With the template form the provider receives OrderId = 42 and Customer = "Ada" as separate properties, so you can search for OrderId = 42, group by customer, or count how many times the template "Order {OrderId} placed by {Customer}" fired. With interpolation you only get opaque text, and you also pay for building the string even when the level is disabled.

Placeholders are matched to arguments by position, not by name. The names are for humans and log systems, so give them PascalCase names that describe the value.

An exception goes in as the first argument, which lets providers print the stack trace and keep it separate from the message: log.LogError(ex, "Payment failed for {Customer}", customer).

Scopes: context for a group of lines

A scope attaches context to every line logged inside a using block, without repeating it in each message. Typical context is a request id, a tenant or an order number. Scopes can nest.

C# Structured properties, scopes and exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at the second line of the output (this provider prints only our own scopes): the same OrderId placeholder arrives as a property named OrderId, the scope's RequestId is attached automatically, and the exception travels separately from the message. The scope with the format string "Payment {Gateway}" also exposes Gateway as a property. Kestrel and the hosting layer already open a scope for each request that carries identifiers such as the trace id (the console provider shows it when you enable IncludeScopes), which is how all the lines belonging to one request can be found together.

LoggerMessage: logging without allocation

Calling log.LogInformation("...", a, b) has small costs: the arguments are boxed into an object array and the template is parsed on first use. For code that logs thousands of times per second, .NET offers LoggerMessage, which pre-parses the template once and avoids the boxing.

The preferred form is the source generator: you declare a partial method with [LoggerMessage], and the compiler writes the body.

C#
public static partial class Log
{
    [LoggerMessage(EventId = 1001, Level = LogLevel.Information,
        Message = "Order {OrderId} shipped to {City}")]
    public static partial void OrderShipped(this ILogger logger, int orderId, string city);
}

// usage
logger.OrderShipped(42, "Oslo");

Source generators are not available in the single-file runner on this site, so the [LoggerMessage] example above is read-only. In a real project (with the normal SDK) it works out of the box. The runner can run the older, non-generated form LoggerMessage.Define, which gives the same benefits and is shown next.

Another cheap habit is checking IsEnabled before building expensive arguments, such as serializing a big object just for a Debug line.

C# LoggerMessage.Define, IsEnabled and request logging middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The request log line is written in a finally block, so it appears even when the endpoint throws, and it reads the status code after the response has been produced. Note that ExpensiveDump never prints: the IsEnabled guard kept it from running. The logger factory adds the Program category for the ILogger<Program> parameter.

You rarely need to hand-write request logging. ASP.NET Core ships the Microsoft.AspNetCore.Hosting.Diagnostics category, which already logs "request starting" and "request finished" at Information with the duration, and an optional HTTP logging middleware (AddHttpLogging and UseHttpLogging) that can record selected headers and bodies. Treat those bodies as sensitive: they can contain passwords and personal data.

What to log, and what never to log

  • Log events and decisions, not every line of code. "Order 42 shipped" is useful; "entering method" is noise.
  • Pick levels by who needs to act. Warning means someone may want to look; Error means an operation failed.
  • Never log secrets or personal data: passwords, tokens, full card numbers, session cookies. Logs are copied, retained and read by many people.
  • Log an exception once. Catch it where you can handle it, or let the global handler log it (Error Handling and Problem Details). Logging at every layer produces duplicate stack traces.
  • Keep templates constant. Do not build the template string from data.

Logs answer "what happened?". For "how often and how slow?" and "which services did this request touch?", you will add metrics and traces, which the lesson on observability covers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the generic argument in ILogger<Checkout> control?

    ILogger<T> uses the full name of T as the category. Filters such as AddFilter("MyShop", LogLevel.Debug) match on category prefixes.
  2. 2. Which call keeps the order id as a searchable property in a structured logging system?

    Only the template form hands the provider a named property (OrderId) separate from the text. The other forms turn the value into plain text before logging sees it.
  3. 3. You set SetMinimumLevel(Information) and AddFilter("Microsoft", Warning). What happens to an Information line from the category Microsoft.AspNetCore.Routing?

    Category filters override the general minimum, and the most specific matching prefix wins. Microsoft means Warning and up for everything under it.
  4. 4. What is the benefit of a scope created with BeginScope?

    A scope supplies context that providers that support scopes add to each entry, so you do not repeat it in every message.
  5. 5. Why does this site show LoggerMessage.Define instead of [LoggerMessage] in its live examples?

    The [LoggerMessage] attribute relies on a source generator that is not available in the runner. In a normal project it is the preferred form.

Summary

  • Ask for ILogger<T> through dependency injection; T becomes the category.
  • Levels run from Trace to Critical; a minimum level and category-prefix filters (code or appsettings.json) decide what is written.
  • Use message templates with named placeholders, never string interpolation, so values stay structured; pass an exception as the first argument.
  • BeginScope attaches context to all lines inside a block; the framework opens a scope per request.
  • LoggerMessage (generated with [LoggerMessage], or LoggerMessage.Define) avoids boxing in hot paths; IsEnabled guards expensive arguments.
  • Log decisions and failures, never secrets, and log each exception once.

Next: JSON Serialization in APIs