Logging
When something goes wrong in production, logs are often the only record of what happened. ASP.NET Core ships with a logging system built on Microsoft.Extensions.Logging: you write log messages through ILogger, and configurable providers send them to the console, the debug window, files, or a monitoring service.
Writing log messages
Ask DI for an ILogger<T>. The type argument becomes the category — usually the class doing the logging — so you can tell where each message came from:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/todos/{id:int}", (int id, ILogger<Program> logger) =>
{
logger.LogInformation("Fetching todo {TodoId}", id);
if (id > 3)
{
logger.LogWarning("Todo {TodoId} not found", id);
return Results.NotFound();
}
return Results.Ok(new { id, title = "Buy milk" });
});
app.Run();With the default console provider, each entry shows the level, the category and an event ID in brackets, followed by the message on an indented line:
$ curl -s -o /dev/null localhost:5000/todos/2
$ curl -s -o /dev/null localhost:5000/todos/9info: Program[0]
Fetching todo 2
info: Program[0]
Fetching todo 9
warn: Program[0]
Todo 9 not found
(The log lines appear in the terminal where dotnet run is running, not in curl's output.)
Log levels
| Level | Method | Console prefix | Use for |
|---|---|---|---|
| Trace (0) | LogTrace |
trce |
very detailed diagnostics, may contain sensitive data |
| Debug (1) | LogDebug |
dbug |
development-time details |
| Information (2) | LogInformation |
info |
normal flow: request handled, order placed |
| Warning (3) | LogWarning |
warn |
unexpected but handled: not found, retry |
| Error (4) | LogError |
fail |
a failure in the current operation |
| Critical (5) | LogCritical |
crit |
the whole app is in trouble |
A minimum level filters out everything below it. It is configured per category in appsettings.json — the longest matching category prefix wins:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"TodoApi.Data": "Debug"
}
}
}The program below implements that filtering rule: find the most specific prefix for a category, then compare levels.
using System;
using System.Collections.Generic;
using System.Linq;
var rules = new Dictionary<string, Level>
{
["Default"] = Level.Information,
["Microsoft.AspNetCore"] = Level.Warning,
["TodoApi.Data"] = Level.Debug,
};
Level MinimumFor(string category) =>
rules.Where(r => r.Key != "Default" && category.StartsWith(r.Key))
.OrderByDescending(r => r.Key.Length)
.Select(r => r.Value)
.DefaultIfEmpty(rules["Default"])
.First();
var attempts = new (string Category, Level Level, string Message)[]
{
("TodoApi.Endpoints", Level.Information, "Listing todos"),
("TodoApi.Endpoints", Level.Debug, "Query took 3 ms"),
("TodoApi.Data.TodoRepository", Level.Debug, "SELECT * FROM Todos"),
("Microsoft.AspNetCore.Routing.EndpointMiddleware", Level.Information, "Executing endpoint"),
("Microsoft.AspNetCore.Server.Kestrel", Level.Warning, "Connection reset"),
};
foreach (var (category, level, message) in attempts)
{
bool enabled = level >= MinimumFor(category);
Console.WriteLine(quot;{(enabled ? "LOG " : "skip")} {level,-11} {category}: {message}");
}
enum Level { Trace, Debug, Information, Warning, Error, Critical }LOG Information TodoApi.Endpoints: Listing todos
skip Debug TodoApi.Endpoints: Query took 3 ms
LOG Debug TodoApi.Data.TodoRepository: SELECT * FROM Todos
skip Information Microsoft.AspNetCore.Routing.EndpointMiddleware: Executing endpoint
LOG Warning Microsoft.AspNetCore.Server.Kestrel: Connection reset
Tip: Setting
Microsoft.AspNetCoretoInformationtemporarily is a great way to see routing decisions and request timings while debugging.
Message templates and structured logging
Notice the message "Fetching todo {TodoId}" is not an interpolated string. It is a message template: the placeholders are filled from the arguments by position, and each value is also kept as a named property. Providers like Seq, Application Insights or OpenTelemetry store TodoId = 9 as a searchable field, so you can query "all warnings for TodoId 9".
// Good: structured, cheap when the level is disabled
logger.LogInformation("Order {OrderId} placed by {UserName}", order.Id, user.Name);
// Avoid: the string is built even when Information is off, and the fields are lost
logger.LogInformation(quot;Order {order.Id} placed by {user.Name}");Here is a simplified template renderer that shows both outputs — the human-readable text and the captured properties:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
static (string Text, Dictionary<string, object> Props) Render(string template, params object[] args)
{
var props = new Dictionary<string, object>();
int i = 0;
string text = Regex.Replace(template, @"\{(\w+)\}", m =>
{
object value = args[i++];
props[m.Groups[1].Value] = value;
return value.ToString();
});
props["{OriginalFormat}"] = template;
return (text, props);
}
var (text, props) = Render("Order {OrderId} placed by {UserName} for {Total}", 1042, "linh", 59.90m);
Console.WriteLine(text);
foreach (var (name, value) in props)
Console.WriteLine(quot; {name} = {value}");Order 1042 placed by linh for 59.90
OrderId = 1042
UserName = linh
Total = 59.90
{OriginalFormat} = Order {OrderId} placed by {UserName} for {Total}
Exceptions and high-performance logging
Pass an exception as the first argument so providers record its type and stack trace:
catch (DbUpdateException ex)
{
logger.LogError(ex, "Saving todo {TodoId} failed", id);
}For hot paths, the [LoggerMessage] source generator creates strongly-typed, allocation-free logging methods at compile time:
public static partial class Log
{
[LoggerMessage(EventId = 1001, Level = LogLevel.Information, Message = "Todo {TodoId} completed")]
public static partial void TodoCompleted(ILogger logger, int todoId);
}
// usage
Log.TodoCompleted(logger, todo.Id); // console: info: TodoApi.TodoService[1001]Test yourself
What is the console prefix for a message written with LogError?
- err
- error
- fail
- crit
Why prefer LogInformation("Todo {Id}", id) over LogInformation(quot;Todo {id}")?
- Interpolated strings don't compile with ILogger
- The template keeps
Idas a structured property and avoids formatting when the level is disabled - Templates are required for the console provider
- Interpolation always throws at runtime
Default is Information and Microsoft.AspNetCore is Warning. Is an Information message from category Microsoft.AspNetCore.Routing logged?
- No
- Yes
- Only in Development
- Only if it has an event ID