Introduction
Instead of beginning observability work by immediately adding Serilog or OpenTelemetry, first understand the application model and built-in logging infrastructure of ASP.NET Core. In this lesson, we will create the shared .NET 10 Web API project used throughout the course. We will define its layers and folders, examine Dependency Injection (DI) lifetimes, and write our first log entries with ILogger.
This foundation matters because later lessons will add Serilog, file and centralized logging, correlation IDs, request logging, and OpenTelemetry to the same project. Without a clear structure and appropriate log levels, advanced tools only produce more data; they do not automatically create useful observability.
1. Creating the shared project and folder structure
Create the solution folder and a controller-based Web API project from a terminal:
mkdir ObservabilityCourse
cd ObservabilityCourse
dotnet new sln -n ObservabilityCourse
dotnet new webapi --use-controllers -f net10.0 -o src/ObservabilityDemo.Api
dotnet sln add src/ObservabilityDemo.Api/ObservabilityDemo.Api.csproj
dotnet build
dotnet run --project src/ObservabilityDemo.ApiWe will use the following structure by the end of this lesson:
ObservabilityCourse/
├── ObservabilityCourse.sln
└── src/
└── ObservabilityDemo.Api/
├── Controllers/
│ └── DiagnosticsController.cs
├── Application/
│ └── DiagnosticsService.cs
├── Domain/
│ └── DiagnosticsResult.cs
├── Infrastructure/
├── Program.cs
├── appsettings.json
├── appsettings.Development.json
└── ObservabilityDemo.Api.csprojThe goal in this first lesson is not to create many separate projects, but to make responsibilities visible from the beginning. Controllers represent the HTTP boundary, Application contains use cases, Domain contains business models, and Infrastructure represents technical concerns such as databases, external services, and future logging or telemetry adapters.
Layer responsibilities
- API layer: Receives and validates HTTP requests and returns appropriate HTTP responses.
- Application layer: Executes use cases. The business workflow should be understandable here.
- Domain layer: Contains meaningful application models and business rules.
- Infrastructure layer: Contains technical details such as databases, file systems, messaging, and external HTTP services.
Log calls should generally be close to the layer where the relevant workflow occurs. Instead of recording only “request received” in a controller, record a failed business rule or unavailable external service in the relevant application or infrastructure component.
2. Dependency Injection and service lifetimes
ASP.NET Core manages services inside a DI container. When a class receives its dependencies through a constructor instead of creating them itself, the application becomes easier to test and configure.
| Lifetime | Description | Typical use |
|---|---|---|
| Transient | A new instance is created each time it is requested. | Lightweight stateless services |
| Scoped | The same instance is used during one web request. | Request-bound services and DbContext |
| Singleton | One instance is used for the lifetime of the application. | Shared, thread-safe services with controlled state |
Let us create a stateless application service. Add Application/DiagnosticsService.cs:
using Microsoft.Extensions.Logging;
namespace ObservabilityDemo.Api.Application;
public sealed class DiagnosticsService
{
private readonly ILogger<DiagnosticsService> _logger;
public DiagnosticsService(ILogger<DiagnosticsService> logger)
{
_logger = logger;
}
public string GetStatus()
{
_logger.LogDebug("Diagnostics service is preparing the status response.");
return "Application is running";
}
}This service could be registered as either transient or scoped. Because it is stateless, we will initially use Transient. Add the following registration to Program.cs:
builder.Services.AddTransient<DiagnosticsService>();Lifetime mismatches can cause problems, such as a singleton service receiving a scoped service through its constructor. A database context or another request-scoped dependency should not be directly injected into a singleton service.
3. The ILogger infrastructure
ILogger<T> usually creates a logger category from the full name of type T. This makes it possible to identify and filter the class that produced a log. A logger should not be created with new; it should be obtained through DI.
Add Controllers/DiagnosticsController.cs:
using Microsoft.AspNetCore.Mvc;
using ObservabilityDemo.Api.Application;
namespace ObservabilityDemo.Api.Controllers;
[ApiController]
[Route("api/diagnostics")]
public sealed class DiagnosticsController : ControllerBase
{
private readonly ILogger<DiagnosticsController> _logger;
private readonly DiagnosticsService _diagnosticsService;
public DiagnosticsController(
ILogger<DiagnosticsController> logger,
DiagnosticsService diagnosticsService)
{
_logger = logger;
_diagnosticsService = diagnosticsService;
}
[HttpGet("status")]
public IActionResult GetStatus()
{
_logger.LogInformation("Status endpoint was requested.");
var status = _diagnosticsService.GetStatus();
_logger.LogInformation("Status endpoint completed with status {Status}.", status);
return Ok(new { status });
}
}The {Status} expression is a structured logging message-template property. Instead of concatenating the value into text, the property is passed separately to the provider. This will make filtering easier when we later use Serilog or a centralized log system.
4. Log levels
Log levels indicate both severity and expected volume. ASP.NET Core levels range from low-detail diagnostics to high-severity failures:
| Level | When to use it | Example |
|---|---|---|
| Trace | Extremely detailed diagnostics, usually for temporary investigation | Every intermediate step of an algorithm |
| Debug | Development and troubleshooting information | The result of a cache lookup |
| Information | Normal application flow | A workflow started or completed |
| Warning | An unexpected condition that does not stop the operation | Optional data was not found |
| Error | The current operation failed | A database query failed |
| Critical | A failure affects the application or a critical capability | Permanent data loss or exhausted disk space |
The following method demonstrates the different levels:
public void DemonstrateLevels()
{
_logger.LogTrace("Trace: detailed execution step {Step}.", 1);
_logger.LogDebug("Debug: cache lookup completed.");
_logger.LogInformation("Information: report generation started.");
_logger.LogWarning("Warning: optional profile data was not found for user {UserId}.", 42);
try
{
throw new InvalidOperationException("Demo failure");
}
catch (Exception exception)
{
_logger.LogError(exception, "Error: report generation failed for user {UserId}.", 42);
}
_logger.LogCritical("Critical: the application cannot reach its required storage.");
}When logging an exception, pass the exception object as a separate argument. Logging only exception.Message loses diagnostic information such as the exception type and stack trace.
5. Configuring Program.cs and appsettings.json
You can simplify the template-generated Program.cs as follows:
using ObservabilityDemo.Api.Application;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddOpenApi();
builder.Services.AddTransient<DiagnosticsService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseHttpsRedirection();
app.MapControllers();
app.Run();The default host adds the built-in logging providers. Managing log levels through configuration instead of hard-coding them in C# makes the application more flexible. Update appsettings.json as follows:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"ObservabilityDemo.Api": "Debug"
}
},
"AllowedHosts": "*"
}With this configuration, Debug and higher messages are enabled for application categories, while Warning and higher messages are enabled for ASP.NET Core categories. For example, a LogTrace call will not normally be displayed.
To investigate the application in more detail during development, add a specific configuration to appsettings.Development.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"ObservabilityDemo.Api": "Trace"
}
}
}Enabling Trace or Debug for every category in production can create high volume, storage costs, and sensitive-data risks. Prefer enabling a detailed level temporarily for only the category being investigated.
6. Testing the application
Run the application:
dotnet run --project src/ObservabilityDemo.ApiUse the address displayed in the terminal to call the endpoint:
curl -k https://localhost:7001/api/diagnostics/statusThe port may be different on your machine. The expected response is approximately:
{"status":"Application is running"}The console output should include the controller and service categories together with Information and Debug messages. If the level in appsettings.Development.json is set to Information, the Debug message from the service will be filtered out.
7. Common mistakes
- Using string interpolation: Prefer the
"User {UserId} loaded"message template over$"User {userId} loaded". - Using Error for everything: Error means the current operation failed; Warning means an abnormal but manageable condition.
- Discarding the exception: Pass the exception as a separate logger argument instead of converting it into text.
- Writing sensitive data: Do not log passwords, access tokens, cookies, personal data, or payment information.
- Enabling Trace in production: Unbounded detail can increase performance and storage costs.
- Choosing the wrong lifetime: Do not directly move a scoped dependency into a singleton service.
- Logging only in controllers: Business decisions and external-system failures should be logged in the relevant service layer.
8. Short practice exercise
Add a GET api/diagnostics/failure endpoint to DiagnosticsController. It should deliberately create an InvalidOperationException, record the exception with LogError, and return a 500 response to the client. Then answer these questions:
- Why is this event Error rather than Information?
- Which values should be represented as structured properties in the log?
- How would you make this endpoint's Debug-level diagnostics visible only during development?
Conclusion
In this lesson, we created the shared .NET 10 Web API, defined layer and folder responsibilities, examined DI lifetimes, and produced our first structured log records with ILogger<T>. We also learned to select Trace, Debug, Information, Warning, Error, and Critical according to the impact of an event.
In the next lesson, we will add Serilog on top of this built-in infrastructure. We will produce richer properties, route events to different sinks, and create a log stream that can be analyzed effectively in production.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection