Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 182 ยท Dependency Injection and Hosting

Logging

Learn logging in C# with Microsoft.Extensions.Logging - ILogger<T>, log levels, structured message templates, scopes, filtering, custom providers, LoggerMessage and common pitfalls.

When a program runs on your laptop, you watch it. When it runs on a server at three in the morning, nobody watches it, and the only thing that tells you what happened is the log. Good logging is the difference between "the site is broken, no idea why" and "the payment call for order 4711 timed out after 3 retries".

.NET has one logging system that nearly every library uses: the Microsoft.Extensions.Logging abstractions. Your code asks for an ILogger<T>, writes messages with a level, and the application decides where those messages go (console, files, a cloud service) through providers. ASP.NET Core, Entity Framework Core and the generic host all log through the same interfaces, so your messages and theirs end up in one stream.

In this lesson you will log with levels, write structured message templates, add scopes, filter noise, build your own provider, and learn the pitfalls that experienced developers watch for.

Logging is part of the ASP.NET Core shared framework, which our runner includes. In your own projects it comes with the web SDK; for console apps you add the Microsoft.Extensions.Logging NuGet package (and Microsoft.Extensions.Logging.Console for the console provider).

ILogger, loggers and providers

There are three pieces:

  • ILogger: the object your code writes to. It has methods such as LogInformation and LogError.
  • ILoggerFactory: creates loggers. Each logger belongs to a category, a string that says who is writing. By convention the category is the full class name.
  • Providers (ILoggerProvider): receive every message and send it somewhere. You can register several at once.

ILogger<T> is a logger whose category is the full name of T. Ask for it in a constructor and dependency injection supplies it (Dependency Injection explains how):

C# The first logger

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.

LoggerFactory.Create is how you build a factory without a host. Inside a host (or an ASP.NET Core app) you do not create it yourself; you configure builder.Logging and the container hands out ILogger<T> everywhere.

Every line begins with the level and the category (info: OrderService[0]). The [0] is the event id, an optional number you can attach to a message to identify its kind. Level names are shortened to four letters in the console: trce, dbug, info, warn, fail, crit.

Console output is written by a background thread so logging does not slow your code down. If you mix Console.WriteLine and the console logger, their lines can arrive out of order. The examples below therefore use a provider that collects lines in memory whenever the order matters.

Log levels

A level says how important a message is. There are six, from least to most severe:

Level Typical use
Trace Very detailed flow, may contain sensitive data. Off in production.
Debug Useful while developing: values of variables, branch taken.
Information Normal events worth knowing: "order placed", "service started".
Warning Something unexpected, but the program carries on: a retry, a fallback.
Error An operation failed. Usually comes with an exception.
Critical The application or machine is in serious trouble: out of disk, lost the database.

There is also LogLevel.None, used only as a filter setting to turn everything off.

Each level has a method: LogTrace, LogDebug, LogInformation, LogWarning, LogError, LogCritical. The general form is logger.Log(LogLevel.Warning, ...).

The minimum level decides what is kept. Anything below it is thrown away before any formatting work happens. Production usually runs at Information or Warning; while hunting a bug you temporarily lower it to Debug.

To see the effect without console noise, here is a tiny in-memory provider. Providers are covered fully later; for now treat MemoryLogs as "a list of lines":

C# The minimum level filters messages

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 first run keeps five messages (Debug and above), the second only three (Warning, Error and Critical). Trace never appears because a minimum of Debug already excludes it.

When you configure a minimum level for a whole factory, providers can still apply their own stricter filters. The next sections show how filtering is configured per category.

Message templates and structured logging

The most important habit in .NET logging is this: write a template, not an interpolated string.

C#
// Good: a template with named placeholders
logger.LogInformation("User {UserId} bought {Count} items", userId, count);

// Avoid: the message is built before the logger even looks at the level
logger.LogInformation($"User {userId} bought {count} items");

In the template, and are placeholders. The arguments fill them by position, not by name: the first argument goes into the first placeholder, whatever you called it. The names matter for something else: they become properties of the log record. A structured provider (Seq, Elasticsearch, Application Insights, OpenTelemetry) stores UserId=42 and Count=3 as separate fields, so you can search for "all messages where UserId is 42" instead of grepping text.

Interpolation throws that away. After $"User {userId}..." is evaluated there is only one flat string, and the string was built even when the level was disabled and the message gets discarded. With a template the formatting only happens if somebody is listening.

We can look at the structured data with our own provider. The state passed to Log is a list of key/value pairs, which includes the original template under the key :

C# Seeing the structure behind a message

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.

Notice three things in the output:

  1. Each placeholder became a named property (UserId, Total), and the original template is kept as .
  2. A format specifier such as {Total:C} is applied when the message text is produced (the sandbox has no culture data, so the currency sign prints as the generic ยค), while the property keeps the raw value 19.5, so a database can still sort by it.
  3. First {B} then {A} received "one" for B and "two" for A: positions, not names. Keep names and argument order in sync, or your structured data will be wrong.

Template rules worth remembering:

  • Use PascalCase placeholder names (, not ), a convention shared by most tooling.
  • Use the same name for the same concept everywhere (UserId, never user, uid and userId in three places), so searches work.
  • To print a literal brace, double it: {{ and }}.
  • Do not put sensitive data (passwords, tokens, full card numbers) into logs. Logs are copied, shipped and kept for months.

Logging exceptions

To log a failure, pass the exception as the first argument, before the template:

C#
catch (Exception ex)
{
    logger.LogError(ex, "Could not import file {FileName}", fileName);
}

The provider receives the exception as a separate object and can print the type, message and stack trace, or store them in structured fields. Never write logger.LogError("Failed: " + ex.Message). You lose the stack trace and the inner exceptions, and that is exactly what you need to debug the problem.

C# An exception is part of the log record

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 console logger prints the message first and the exception below it, with its stack trace. Remember: log an exception once, where you handle it. If every layer catches, logs and rethrows, one failure produces five identical entries and nobody can tell which one matters.

Scopes: context for a group of messages

A scope attaches extra data to every message written while it is open. It is perfect for request ids, order numbers or tenant names that you do not want to repeat in each call.

C#
using (logger.BeginScope("Order {OrderId}", 4711))
{
    logger.LogInformation("Validating");
    logger.LogInformation("Charging card");
}

BeginScope returns an IDisposable; the scope ends when you dispose it. Scopes flow along with async code, so they continue to apply after an await. Whether the scope is shown depends on the provider: the console provider needs IncludeScopes = true.

C# Scopes in the console output

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.

Scopes nest, and a message shows every scope that is open at that moment. In ASP.NET Core, the framework already opens a scope per request containing the request id and trace id, so every message you log while handling a request carries it automatically.

Filtering by category

You rarely want one global level. Typically you want your own code at Debug but the chatty framework at Warning. Filters match by category prefix: the most specific matching rule wins.

C#
builder.Logging.SetMinimumLevel(LogLevel.Information);
builder.Logging.AddFilter("Microsoft", LogLevel.Warning);
builder.Logging.AddFilter("MyApp.Billing", LogLevel.Debug);

The same thing in appsettings.json, which is how most real apps do it (read-only example, because our runner has no files to load from):

JSON
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "MyApp.Billing": "Debug"
    }
  }
}

A filter can also target one provider: "Console": { "LogLevel": { "Default": "Warning" } } affects only the console provider. Because the settings come from configuration, you can change the level per environment, or in some setups at runtime, without recompiling.

You can load the same shape from an in-memory configuration, which makes it runnable here:

C# Filters by category prefix

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.

MyApp.Billing.Invoices starts with MyApp.Billing, so it gets Debug. MyApp.Shipping matches nothing specific and falls back to Default, which is Warning, so its debug line vanishes.

Writing your own provider

You have already seen the shape. A provider implements ILoggerProvider (a factory for loggers, one per category) and each logger implements ILogger with three members:

  • IsEnabled(level): should this level be processed? Return false and callers can skip expensive work.
  • BeginScope(state): start a scope; return an IDisposable or null.
  • Log(...): receive a message. Call formatter(state, exception) to get the final text.

Real providers write to a file, a queue or a network service. They must be thread safe, because many threads log at once, and they should be fast: a slow Log method slows the code that logs. That is why serious providers put messages into a queue (see Channels) and write them from a background worker.

In practice you almost never write a provider. Use Serilog, NLog, OpenTelemetry or your cloud's provider (each is a NuGet package) and keep ILogger<T> in your code. That is the point of the abstraction: you can swap the destination without changing a single logging call.

LoggerMessage: high-performance logging

Calls like logger.LogInformation("Order {OrderId}", id) allocate a bit: the arguments are boxed into an object array and the template is parsed. For code that runs millions of times, the logger message source generator removes that cost. You declare a partial method with an attribute and the compiler writes the efficient code:

C#
// Read-only: the generator runs in the normal build, shown here for reference.
public static partial class Log
{
    [LoggerMessage(EventId = 1001, Level = LogLevel.Information,
        Message = "Order {OrderId} placed for {Total}")]
    public static partial void OrderPlaced(ILogger logger, int orderId, decimal total);
}

// usage
Log.OrderPlaced(logger, 4711, 19.5m);

Benefits: no boxing, the level check happens first, the template is parsed once, event ids are explicit, and the compiler checks that placeholder names match the parameters. Use it in hot paths and in libraries; in ordinary application code the plain extension methods are fine.

Without the generator you can get a similar effect with the older LoggerMessage.Define, which returns a cached Action<ILogger, ...> delegate:

C# LoggerMessage.Define

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.

Note that the event id 1001 shows up in the output in place of the [0] you saw before.

Pitfalls professionals avoid

  • String interpolation in log calls. It defeats structured logging and does work even when the level is off. Use templates.
  • Expensive arguments. logger.LogDebug("Data: {Data}", BuildBigReport()) runs BuildBigReport() even if Debug is disabled. Guard it: if (logger.IsEnabled(LogLevel.Debug)) { ... }.
  • Logging secrets and personal data. Passwords, tokens, health data. Treat logs as public.
  • Log-and-throw. Logging an exception and then rethrowing it makes the same error appear many times. Log at the layer that handles it.
  • Wrong levels. If everything is Error, nothing is. A user typing a wrong password is Information or Warning, not Error.
  • Logging in tight loops. A line per item for a million items will cost more than the work. Log a summary or sample.
  • Using Console.WriteLine for diagnostics in services. It cannot be filtered, has no level, no category, no scopes. Use ILogger.
  • Forgetting to flush. Buffered providers write in the background. A host flushes them on shutdown; a hand-built factory needs Dispose(), which is why the examples above use using.

When to use what

  • Use ILogger<T> in every class that has something worth saying, injected through the constructor.
  • Pick levels by the audience: Debug for developers, Information for operators, Warning and Error for whoever gets paged.
  • Prefer templates with stable names; they are your future search fields.
  • Use scopes for context that spans several messages (request id, order id).
  • Use LoggerMessage where performance matters; otherwise keep it simple.

Logging is not the same as metrics (numbers over time) or tracing (the path of one request across services). .NET handles those with System.Diagnostics.Metrics and Activity, and OpenTelemetry collects all three. Logs are best for events and explanations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which call follows the recommended way of writing a log message with a value?

    A template with a named placeholder keeps the value as a separate property for structured providers and skips formatting when the level is disabled. Interpolation and concatenation produce one flat string up front.
  2. 2. A logger has minimum level Information. Which of these messages is discarded?

    Debug is below Information, so it is filtered out. Information itself and everything more severe are kept.
  3. 3. How do you log an exception with its stack trace?

    Pass the exception object as the first argument. The provider then receives the whole exception, including type, stack trace and inner exceptions.
  4. 4. In logger.LogInformation("First {B} then {A}", "one", "two"), what does receive?

    Placeholders are filled in order of appearance: {B} gets the first argument and {A} the second. The names only become property names in the log record.
  5. 5. What does a scope do?

    BeginScope returns an IDisposable; while it is open, providers that support scopes show or store its data with every message, for example a request id.

Summary

  • Code writes to ILogger<T>; providers decide where messages go. Inject loggers instead of creating them.
  • The six levels are Trace, Debug, Information, Warning, Error and Critical. The minimum level and category filters decide what is kept.
  • Write message templates with PascalCase placeholders; arguments fill them by position and the names become structured properties.
  • Pass exceptions as the first argument and log each failure once.
  • Scopes add context to all messages inside them; filters match by category prefix.
  • Use [LoggerMessage] or LoggerMessage.Define in hot paths, guard expensive arguments with IsEnabled, and never log secrets.

Next: The Generic Host and BackgroundService