Configuration, options and logging
Course contents (16 lessons)
- The type system
- Records, structs and value equality
- Interfaces and abstract classes
- Generics and constraints
- Delegates, events and lambdas
- Querying and matching data
- LINQ in depth: deferred execution, grouping and joins
- IEnumerable versus IQueryable
- Pattern matching in modern C#
- Async and await: how Task really works
- Async patterns: cancellation, timeouts and async streams
- Application structure
- Dependency injection and service lifetimes
- Configuration, options and logging
- Data and web
- Entity Framework Core basics: DbContext, migrations and queries
- Building a minimal API with ASP.NET Core
- Unit testing with xunit
- Performance and the final project
- Performance basics: Span of T and fewer allocations
- Final project: a notes API with EF Core, DI and logging
Settings do not belong in code
A connection string, an API key, the number of items per page, a feature flag. These change between your laptop, the test server and production. If they are hard-coded, you rebuild to change them, and you will eventually commit a secret to source control. .NET has a configuration system that reads values from several places and merges them, so one program works everywhere.
How configuration works
When you use the generic host, Host.CreateApplicationBuilder(), it sets up configuration in layers. Later layers override earlier ones:
appsettings.jsonappsettings.{Environment}.json, for exampleappsettings.Development.json- User secrets, in the Development environment
- Environment variables
- Command-line arguments
Keys are hierarchical. In JSON that is nesting. In environment variables you use a double underscore: Shop__PageSize=50 overrides Shop:PageSize in the file. This is how containers and hosting platforms inject production settings without changing any file in the repository.
For the example to run without extra files, I add an in-memory source. In a real project you would put these values in appsettings.json instead:
{
"Shop": { "Name": "Hussain Books", "PageSize": 20, "FreeShippingOver": 5000 },
"Logging": { "LogLevel": { "Default": "Information" } }
}
Create a console project and run dotnet add package Microsoft.Extensions.Hosting.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
["Shop:Name"] = "Hussain Books",
["Shop:PageSize"] = "20",
["Shop:FreeShippingOver"] = "5000"
});
builder.Services.Configure<ShopOptions>(builder.Configuration.GetSection("Shop"));
builder.Services.AddTransient<CheckoutService>();
using IHost host = builder.Build();
var checkout = host.Services.GetRequiredService<CheckoutService>();
checkout.Process("A-1001", 3200m);
checkout.Process("A-1002", 7400m);
checkout.Process("A-1003", -5m);
class ShopOptions
{
public string Name { get; set; } = "";
public int PageSize { get; set; } = 10;
public decimal FreeShippingOver { get; set; }
}
class CheckoutService(IOptions<ShopOptions> options, ILogger<CheckoutService> logger)
{
private readonly ShopOptions _shop = options.Value;
public void Process(string orderId, decimal total)
{
if (total <= 0)
{
logger.LogWarning("Order {OrderId} rejected: total {Total} is not positive", orderId, total);
return;
}
decimal shipping = total >= _shop.FreeShippingOver ? 0m : 250m;
logger.LogInformation(
"Order {OrderId} at {Shop}: total {Total}, shipping {Shipping}",
orderId, _shop.Name, total, shipping);
try
{
if (total > 7000m) throw new InvalidOperationException("Manual review required.");
}
catch (Exception ex)
{
logger.LogError(ex, "Order {OrderId} needs attention", orderId);
}
}
}
Walking through it
Host.CreateApplicationBuilder(args) sets up configuration, logging and the DI container together. We add our values, and then bind the Shop section to a ShopOptions class with Configure<ShopOptions>. This is the options pattern. Instead of reading strings like config["Shop:PageSize"] all over the code, you work with a typed object. Typos become compile errors, and numbers are already parsed.
A class asks for IOptions<ShopOptions> in its constructor. Its Value property holds the bound object. There are two cousins. IOptionsSnapshot re-reads settings per request in web apps, and IOptionsMonitor notifies you when the file changes. Start with IOptions unless you need live reload.
Logging goes through ILogger<T>. The type argument becomes the category in the output, so you can see which class wrote each line. Notice the message templates: "Order {OrderId} at {Shop}...". I did not use string interpolation. The placeholders are named, and the values are passed as separate arguments. This is structured logging. A log system such as Seq, Elasticsearch or Application Insights stores OrderId as a searchable field. With interpolation, you would only get a string and lose that ability, and you would also pay the cost of building the string even when the level is turned off.
The log levels, from least to most severe, are Trace, Debug, Information, Warning, Error and Critical. The configuration decides the minimum level that gets written. In production I typically run at Information or Warning, and raise it to Debug for a short time when I am chasing a problem, without a redeploy, by changing an environment variable.
When logging an exception, pass it as the first argument: LogError(ex, "message"). That records the stack trace. Writing ex.Message into the text loses it.
Keeping secrets out of Git
Never put passwords or API keys into appsettings.json in the repository. During development, use user secrets: dotnet user-secrets init and dotnet user-secrets set "Stripe:Key" "...". They are stored in your user profile, outside the project. In production, use environment variables or a secret store from your hosting provider.
Common mistakes
- Logging with string interpolation instead of message templates.
- Logging secrets or personal data. Passwords, tokens and card numbers must not appear in logs.
- Misspelling a section name. The binding silently gives you defaults. Validate important options at startup.
- Forgetting that environment variables win over the file, and then wondering why a value is not changing.
- Logging too much at Information level. A noisy log hides the one line you need.
Try it yourself
- Move the settings to a real
appsettings.jsonfile, set it to copy to the output directory, and remove the in-memory source. - Override
Shop:PageSizewith an environment variable and print the value. - Set the minimum log level to Warning in configuration and observe which lines disappear.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
["Shop:Name"] = "Hussain Books",
["Shop:PageSize"] = "20",
["Shop:FreeShippingOver"] = "5000"
});
builder.Services.Configure<ShopOptions>(builder.Configuration.GetSection("Shop"));
builder.Services.AddTransient<CheckoutService>();
using IHost host = builder.Build();
var checkout = host.Services.GetRequiredService<CheckoutService>();
checkout.Process("A-1001", 3200m);
checkout.Process("A-1002", 7400m);
checkout.Process("A-1003", -5m);
class ShopOptions
{
public string Name { get; set; } = "";
public int PageSize { get; set; } = 10;
public decimal FreeShippingOver { get; set; }
}
class CheckoutService(IOptions<ShopOptions> options, ILogger<CheckoutService> logger)
{
private readonly ShopOptions _shop = options.Value;
public void Process(string orderId, decimal total)
{
if (total <= 0)
{
logger.LogWarning("Order {OrderId} rejected: total {Total} is not positive", orderId, total);
return;
}
decimal shipping = total >= _shop.FreeShippingOver ? 0m : 250m;
logger.LogInformation(
"Order {OrderId} at {Shop}: total {Total}, shipping {Shipping}",
orderId, _shop.Name, total, shipping);
try
{
if (total > 7000m) throw new InvalidOperationException("Manual review required.");
}
catch (Exception ex)
{
logger.LogError(ex, "Order {OrderId} needs attention", orderId);
}
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account