Lesson 17 / 26
Options and Logging
Bind settings to a typed class and write structured logs with ILogger.
Typed settings
The options pattern binds a configuration section to a class, so you read options.PageSize instead of string keys. ILogger<T> is injected like any other service and writes structured messages.
Bind and use
Use message templates with named placeholders rather than string interpolation, so log systems can filter by property.
builder.Services.Configure<ShopOptions>(builder.Configuration.GetSection("Shop"));
app.MapGet("/size", (IOptions<ShopOptions> opt, ILogger<Program> log) =>
{
log.LogInformation("Page size is {PageSize}", opt.Value.PageSize);
return opt.Value.PageSize;
});
public class ShopOptions { public int PageSize { get; set; } = 20; }Do not log secrets
Never log passwords, tokens or full request bodies. Set minimum levels per category in appsettings.json so production does not drown in Debug messages.
Quick check: Why prefer `{PageSize}` placeholders over `$"{pageSize}"` in log calls?
- They compile faster
- They are required by C#
- Values are kept as searchable properties
- They hide values from logs
Answer
Values are kept as searchable properties — Message templates keep the value separate from the text, so tools can query and filter on it.