skip to content

ILogger Categories & Scopes

ILogger<T> writes through providers filtered by category and the Logging:LogLevel section, using message templates, scopes and [LoggerMessage]. Interviewers probe level filtering and hot-path cost.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core 10, how do you inject ILogger<T>, which category does it log under, and how does Logging:LogLevel in appsettings.json decide what is written?

level: juniorimportance: must knowfreq 78%

answer

  1. constructor injection, no per-request logger
  2. category comes from typeof(T)
  3. longest matching prefix wins
  4. Trace 0 up to None 6
  5. template: Microsoft.AspNetCore = Warning

basics

~10 s

Inject ILogger<PickListService> through the constructor; its category is the type's full name, such as Warehouse.Picking.PickListService. Logging:LogLevel maps category prefixes to minimum levels: the longest matching prefix wins, otherwise Default applies.

solid answer

~40 s

You take `ILogger<PickListService>` as a constructor parameter (or a primary-constructor parameter); `AddLogging` registers `ILogger<>` as a singleton open generic, so any service lifetime may inject it. The category is the full type name without generic arguments, nested types joined with a dot, for example `Warehouse.Picking.PickListService`. For a name you choose, inject `ILoggerFactory` and call `CreateLogger("Warehouse.Picking.Waves")`. In `appsettings.json`, `Logging:LogLevel` maps category **prefixes** to a minimum level: `"Warehouse": "Debug"` covers every category that starts with `Warehouse`, the longest matching prefix wins, and `Default` covers everything else. The template writes `Default = Information` and `Microsoft.AspNetCore = Warning`, which hides the framework's per-request information lines. `None` switches a category off, and with no matching rule at all the minimum is `Information`.

code

json · 9 lines
json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Warehouse.Picking": "Debug"
    }
  }
}

go deeper

for a junior

Recall that ILogger<T> arrives through the constructor, that its category is the full type name, and that the template sets Default to Information and Microsoft.AspNetCore to Warning.

for a middle

Explain how the longest matching prefix chooses a level, what None does, how app.Logger and ILoggerFactory.CreateLogger give other categories, and why appsettings.Development.json can override you.

for a senior

Show that you design namespaces as filter hierarchies, raise one area's level on a running app through reloadable configuration, and know which framework categories to quiet without losing warnings.

for a principal

Weigh fleet-wide defaults against per-team overrides: who owns the Logging section, how level changes are audited, and how much Debug volume an incident is allowed to cost.

## Getting a logger ASP.NET Core's logging API lives in `Microsoft.Extensions.Logging`. `WebApplication.CreateBuilder` calls `AddLogging`, which registers `ILoggerFactory` (implemented by `LoggerFactory`) and the open generic `ILogger<>` (implemented by `Logger<T>`), **both as singletons**. In a warehouse picking service you simply ask for one: ```csharp namespace Warehouse.Picking; public sealed class PickListService(ILogger<PickListService> logger) { public void Release(int orderId, int lineCount) { logger.LogInformation("Released order {OrderId} with {LineCount} lines", orderId, lineCount); logger.LogDebug("Bin lookups cached for order {OrderId}", orderId); } } ``` Because the logger is a singleton, a singleton, scoped or transient service may inject it; there is no per-request logger to worry about. Outside a class, `app.Logger` on `WebApplication` gives a logger whose category is the application name, and `ILoggerFactory.CreateLogger(string)` gives one with any category you choose. ## The category The **category** is a string attached to every entry a logger writes. `Logger<T>` builds it from `typeof(T)`: - the **full name including the namespace**: `Warehouse.Picking.PickListService`, not `PickListService`; - **no generic arguments**: `ILogger<Repository<Order>>` logs under the namespace plus `Repository`; - **nested types joined with a dot** rather than the CLR's `+`. Namespaces therefore become a hierarchy you can filter on, which is why a sensible namespace layout pays off when you need to raise one area's level. ## How Logging:LogLevel chooses a level Levels are ordered `Trace` (0), `Debug`, `Information`, `Warning`, `Error`, `Critical` (5) and `None` (6). A rule sets a **minimum**: everything at that level or above passes, and `None` lets nothing through. ```json { "Logging": { "LogLevel": { "Default": "Warning", "Warehouse": "Debug", "Warehouse.Picking.Replenishment": "None" } } } ``` For each logger the factory picks one rule, following the comments in `LoggerRuleSelector`: 1. Rules for the specific provider beat rules without a provider (that part matters once you add `Logging:Console:LogLevel`). 2. Among the remaining rules, the one with the **longest category prefix** that matches wins; matching is a case-insensitive `StartsWith`, and one `*` wildcard is allowed. 3. If no category matches, the rule without a category (`Default`) applies. 4. When two rules match equally well, the one added last wins. 5. With no applicable rule at all, the global minimum applies, which `AddLogging` sets to `Information`. With the JSON above, `Warehouse.Picking.PickListService` writes `Debug` and above, `Warehouse.Picking.Replenishment.Planner` writes nothing, and `Microsoft.EntityFrameworkCore.Database.Command` falls back to `Warning`. | Category | Rule that wins | Lowest level written | |---|---|---| | `Warehouse.Picking.PickListService` | `Warehouse` | `Debug` | | `Warehouse.Picking.Replenishment.Planner` | `Warehouse.Picking.Replenishment` | nothing | | `Microsoft.AspNetCore.Routing.EndpointMiddleware` | `Default` | `Warning` | ## What the template writes `dotnet new webapi` writes the same `Logging` block into `appsettings.json` and `appsettings.Development.json`: `Default` = `Information` and `Microsoft.AspNetCore` = `Warning`. The second line is why a fresh app does not print the framework's request-started and request-finished lines: they are `Information` entries under `Microsoft.AspNetCore.Hosting.Diagnostics`. Your own `Information` lines still appear through `Default`. Because `appsettings.{Environment}.json` loads after `appsettings.json`, a key set in the development file replaces the same key from the base file while running in Development; a level that looks right in one file can be overridden by the other. ## Changing levels without code - The filter options are read through `IOptionsMonitor<LoggerFilterOptions>`, so editing `appsettings.json` on a running app (the default JSON source reloads on change) re-applies the rules without a restart. - Environment variables use the double-underscore form, for example `Logging__LogLevel__Warehouse=Debug`. - In code, `builder.Logging.SetMinimumLevel(LogLevel.Warning)` sets the global minimum and `builder.Logging.AddFilter("Warehouse", LogLevel.Debug)` adds a rule of the same kind the JSON produces. The level check itself is cheap: each logger caches the chosen minimum per provider, so a `LogDebug` call under a `Warning` rule returns after a comparison, although the call's arguments have already been built by then.

  • How do you log from Program.cs or from a static helper that has no T to put in ILogger<T>?
    In Program.cs use `app.Logger`, which `WebApplication` creates from `ILoggerFactory` with the application name as its category. Elsewhere inject `ILoggerFactory` and call `CreateLogger("Warehouse.Picking.Labels")`, or pass an `ILogger` into the static method. The chosen string is filtered by `Logging:LogLevel` prefixes exactly like a type name.
  • You set "Warehouse": "Debug" in appsettings.json, yet Debug lines are missing when the app runs in Development. Where do you look first?
    At `appsettings.Development.json`: it loads after the base file, and the template already puts a `Logging:LogLevel` block there. A `Warehouse` key in that file replaces yours, and a provider section there outranks it. Then check environment variables such as `Logging__LogLevel__Warehouse` and any `AddFilter` or `SetMinimumLevel` call in Program.cs.

  • ILogger<T> logs under the bare class name, without the namespace.
  • Logging:LogLevel:Default overrides the more specific category entries.
  • Category keys must match exactly; a prefix such as Warehouse matches nothing.
  • Setting a category to Debug also lets its Trace lines through.
  • ILogger<T> is scoped, so a singleton service cannot inject it.
open as a page

In ASP.NET Core, why pass a message template with arguments to logger.LogInformation instead of an interpolated $"..." string, and how do placeholders bind?

level: middleimportance: must knowfreq 64%

basics

~20 s

A template such as "Picked {Sku} for order {OrderId}" keeps Sku, OrderId and the template as named values that providers can emit as fields. An interpolated string arrives as one finished text, built even when the level is filtered out.

open as a page

In ASP.NET Core, how does ILogger.BeginScope tag each log line during one order's picking, and what makes that scope appear in console output?

level: middleimportance: should knowfreq 48%

basics

~20 s

Wrap the work in using (logger.BeginScope(new Dictionary<string, object?> { ["OrderId"] = id })); every entry written inside it, by any logger and across awaits, carries OrderId. The console shows it only when IncludeScopes is true.

open as a page

In ASP.NET Core 10, which logging providers does WebApplication.CreateBuilder register, and what do ClearProviders and AddJsonConsole change about where log entries go?

level: middleimportance: should knowfreq 42%

basics

~10 s

WebApplication.CreateBuilder registers Console, Debug and EventSource, plus EventLog on Windows. ClearProviders removes every provider registered so far; AddJsonConsole adds the console provider with its formatter set to json, one JSON object per entry.

open as a page

In an ASP.NET Core 10 service logging thousands of pick events per second, what does [LoggerMessage] generate, and when do you still need an ILogger.IsEnabled guard?

level: seniorimportance: should knowfreq 40%

basics

~20 s

[LoggerMessage] on a partial method makes the compiler generate a strongly typed logging method that checks IsEnabled and logs without an object array or boxing. Arguments are still evaluated by the caller, so expensive ones need an explicit IsEnabled guard.

open as a page