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?
answer
- constructor injection, no per-request logger
- category comes from typeof(T)
- longest matching prefix wins
- Trace 0 up to None 6
- template: Microsoft.AspNetCore = Warning
basics
~10 sInject 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 sYou 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{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Warehouse.Picking": "Debug"
}
}
}go deeper
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.
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.
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.
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.