Intermediate 32 min read

Logging Abstractions

ILogger, categories, log levels and providers.

Logging in ASP.NET Core

1. About

PropertyDetails
TitleLogging in ASP.NET Core
SubtitleLog levels, ILogger, structured logging, exception handling, and production monitoring
Category.NET Fundamentals
DifficultyIntermediate
PrerequisitesC#, dependency injection, middleware, configuration and appsettings.json
Previous topicConfiguration & appsettings.json
Next topicMVC

Learning outcomes

After completing this module, you will be able to:

  • Explain logging and why production applications need it.
  • Understand ILogger, ILogger<T>, and logging providers.
  • Choose appropriate log levels.
  • Configure logging through appsettings.json.
  • Use structured logging, scopes, and event IDs.
  • Log exceptions correctly in services, controllers, and middleware.
  • Build a production-oriented logging strategy.
  • Avoid exposing sensitive information through logs.
  • Answer logging interview questions and apply the concepts in a mini project.

2. Introduction

What is logging?

Logging is the process of recording meaningful information about an application's execution so developers and operations teams can understand what happened, when it happened, and why it happened.

Imagine an e-commerce customer tries to place an order. Payment processing fails because the payment provider is temporarily unavailable. The customer sees an error, but the development team needs evidence to investigate it.

Useful log events might record that the order was created, payment processing started, the provider returned an error, and the order could not be completed.

Why does logging exist?

Applications perform thousands or millions of operations. Developers cannot watch every operation in real time. Logging records selected events so they can be examined later, depending on the configured provider and destination.

Problems logging helps solve

ProblemHow logging helps
Unexpected exceptionsRecords the exception and stack trace
Slow API responsesHelps identify slow operations and dependencies
Payment failuresRecords the failure stage and a safe diagnostic reason
Database errorsHelps identify query or connection problems
Production debuggingProvides evidence from real executions
Security investigationsRecords relevant events without exposing secrets
Operational monitoringSupplies events for monitoring and alerting
Support investigationsHelps connect a reported issue with application activity

Logging versus debugging


DebuggingLogging
Often interactiveUsually automatic
Uses breakpoints and a debuggerUses calls such as LogInformation()
Often used during developmentCan be used in every environment
Examines a particular executionRecords selected events across executions

Key idea: Logging does not prevent every failure. It helps you understand failures, diagnose problems, and make better operational decisions.

3. Real-Life Analogy: Hospital Records

A hospital records important events such as admission, tests, medication, and discharge. If a problem occurs, authorized staff can review the record to understand what happened.

HospitalASP.NET Core
Patient recordLog entry
Medical eventApplication event
Failed testApplication or dependency failure
Patient identifierRequest or correlation identifier
Records systemLogging provider and storage system

A useful record says more than "Something happened." It provides a meaningful event and enough safe context to investigate.

Security note: Application logs must follow privacy, retention, and access-control requirements. They should not become an unrestricted record of personal or confidential data.

4. Architecture Diagram

  1. A request reaches the application.
  2. Middleware, controllers, or services execute.
  3. Application code writes a log entry through ILogger.
  4. Filters determine whether the entry should be emitted.
  5. Providers send the entry to configured destinations.
  6. A collection or monitoring system can index the entries and trigger alerts.

A provider does not automatically guarantee permanent storage. Console output may disappear when a process or container stops unless another system collects it.

5. Concept Explanation

5.1 What is a log entry?

A log entry records an event during application execution. Depending on the provider, it can contain:

  • Timestamp: When the event occurred.
  • Level: Importance or severity.
  • Message: What happened.
  • Category: The component that produced the entry.
  • Event ID: An optional identifier for a known event.
  • Exception: Exception details when supplied.
  • Structured properties: Searchable values such as an order ID.
  • Trace information: Identifiers used to connect related operations.

5.2 What is ILogger?

ILogger is an interface from the Microsoft Extensions Logging system. It provides methods to write entries at different levels.

using Microsoft.Extensions.Logging;

public class OrderService
{
    private readonly ILogger<OrderService> _logger;

    public OrderService(ILogger<OrderService> logger)
    {
        _logger = logger;
    }

    public void CreateOrder(int orderId)
    {
        _logger.LogInformation(
            "Creating order {OrderId}", orderId);
    }
}

ILogger<OrderService> is a generic logger whose category is normally based on the fully qualified name of OrderService. This makes it easier to filter logs by component.

Why inject it? Dependency injection provides the correctly configured logger. The class does not need to create its own logging infrastructure.

5.3 The six standard log levels

From least to most severe:

LevelTypical useExample
TraceVery detailed diagnostic eventsEntering a low-level operation
DebugDevelopment and troubleshooting detailsCache lookup result
InformationNormal application milestonesOrder created
WarningUnexpected situation that may recoverRetry required after a temporary failure
ErrorAn operation failedPayment operation failed
CriticalA serious failure affecting application operationRequired subsystem unavailable

Trace and Debug are often disabled or restricted in production because of volume. Information is suitable for meaningful milestones, not every line of code.

Tip: Choose the level based on the operational meaning of the event, not merely on whether the code line looks important.

5.4 What is a logging provider?

A logging provider determines where logs are written.

Common providers include:

  • Console provider.
  • Debug provider.
  • EventSource provider.
  • Windows Event Log provider, where supported.
  • Third-party providers that send logs to files or centralized systems.

ASP.NET Core includes common providers by default in typical web application templates. Additional providers may require a NuGet package and explicit configuration.

5.5 What is a logging category?

The category identifies the source of a log entry. With ILogger<T>, it usually corresponds to the type T.

Example category:

MyApp.Services.OrderService

Categories allow configuration to target specific components or namespaces.

5.6 What is structured logging?

Structured logging records named values separately from the rendered message.

_logger.LogInformation(
    "Order {OrderId} created for customer {CustomerId}",
    orderId,
    customerId);

Here, OrderId and CustomerId are named properties. A compatible provider can index them so an operator can search for a particular order without parsing a text sentence.

Prefer this over string interpolation:

// Less suitable for structured logging:
_logger.LogInformation($"Order {orderId} created");

The interpolated form produces a rendered string before the logging call. The template-and-arguments form preserves structured fields for providers that support them.

5.7 What are logging scopes?

A scope attaches shared context to multiple log entries produced during a logical operation.

using (_logger.BeginScope(
    "Processing order {OrderId}", orderId))
{
    _logger.LogInformation("Payment started");
    _logger.LogInformation("Inventory checked");
}

A provider must support scopes, and scope output must be enabled where required. Use scopes for safe correlation data such as an operation identifier. Do not put secrets or unnecessary personal information in scopes.

5.8 What is an event ID?

An event ID is a numeric identifier, optionally accompanied by a name, that identifies a type of event.

private static readonly EventId OrderCreatedEvent =
    new(1001, nameof(OrderCreatedEvent));

_logger.LogInformation(
    OrderCreatedEvent,
    "Order {OrderId} created",
    orderId);

Event IDs can help teams group and search recurring events. Agree on conventions in larger applications.

5.9 Logging and exceptions

When an exception is available, pass it as the exception argument so providers can capture its details and stack trace.

try
{
    await paymentService.ProcessAsync(orderId, cancellationToken);
}
catch (PaymentProviderException ex)
{
    _logger.LogError(
        ex,
        "Payment processing failed for order {OrderId}",
        orderId);

    throw;
}

Only catch an exception when you can handle it, add useful context, translate it appropriately, or perform necessary cleanup. Avoid logging an exception at every layer and then rethrowing it, because this can create duplicate noisy records.

5.10 Logging and monitoring are related but different

Logging records events. Metrics summarize numerical measurements, such as request duration or failure rate. Distributed tracing connects operations across services.

SignalBest at answering
LogsWhat happened in this particular operation?
MetricsHow often, how many, or how long?
TracesWhere did time go across a distributed request?

Production observability usually combines all three.

6. Important Terminology

TermMeaningExample
Log entryRecord of an event“Order created”
ILoggerLogging abstractionInjected into a service
CategoryName identifying the log sourceOrderService
ProviderDestination adapter for logsConsole provider
Log levelEvent importanceWarning
Structured loggingMessage plus named properties{OrderId}
ScopeContext shared across entriesRequest or operation ID
Event IDIdentifier for an event type1001
FilterRule deciding which events are emittedMinimum level Warning
SinkDestination in some logging librariesCentral log store
Correlation IDIdentifier connecting related workRequest ID
Stack traceCall sequence associated with an exceptionError diagnostics
ObservabilityUnderstanding system behavior from outputsLogs, metrics, traces

7. How It Works Internally

Step-by-step workflow

  1. Application code calls a logging method.
  2. The logger evaluates whether the level is enabled for its category.
  3. If enabled, the logging system passes the event and its data to configured providers.
  4. Each provider formats or exports the event according to its implementation.
  5. A destination receives the entry.
  6. A log collector may enrich, store, index, and retain it.
  7. Engineers search the data or monitoring rules raise alerts.

Filtering behavior and the work performed by providers depend on configuration and implementation. Logging is not a guarantee that every entry is durably stored.

8. Syntax

Common logging methods

_logger.LogTrace("Detailed diagnostic information");
_logger.LogDebug("Debugging information");
_logger.LogInformation("Application milestone");
_logger.LogWarning("Unexpected but recoverable condition");
_logger.LogError("Operation failed");
_logger.LogCritical("Critical system failure");

Structured message syntax

_logger.LogInformation(
    "Order {OrderId} created for {CustomerId}",
    orderId,
    customerId);
  • _logger: The injected logger instance.
  • LogInformation: Writes an event at the Information level.
  • Message template: Describes the event.
  • {OrderId} and {CustomerId}: Named structured properties.
  • orderId and customerId: Values assigned to those properties in order.

The names in the template should match the intended meaning of the arguments.

Exception syntax

_logger.LogError(
    exception,
    "Could not process order {OrderId}",
    orderId);

Pass the exception as the first argument to the overload that accepts it. Do not use only exception.Message when the stack trace and exception type are needed for diagnosis.

Dependency injection syntax

public class InventoryService
{
    private readonly ILogger<InventoryService> _logger;

    public InventoryService(ILogger<InventoryService> logger)
    {
        _logger = logger;
    }
}

ASP.NET Core provides logging through dependency injection in its standard hosting setup. You generally do not need to register ILogger<T> yourself.

9. Code Examples

9.1 Simple example

A minimal .NET 9 console application can use the hosting abstractions and dependency injection.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

var builder = Host.CreateApplicationBuilder(args);

using var host = builder.Build();

var logger = host.Services
    .GetRequiredService<ILogger<Program>>();

logger.LogInformation("Application started");
logger.LogWarning("This is a sample warning");
logger.LogError("This is a sample error");

await host.RunAsync();

This illustrates logger resolution and log levels. For a real hosted service, put ongoing work into a BackgroundService rather than running it before RunAsync.

9.2 Intermediate example: service logging

using Microsoft.Extensions.Logging;

public sealed class OrderService
{
    private readonly ILogger<OrderService> _logger;

    public OrderService(ILogger<OrderService> logger)
    {
        _logger = logger;
    }

    public async Task<bool> CreateOrderAsync(
        int orderId,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Starting order creation for {OrderId}", orderId);

        try
        {
            // Replace this with real database or domain work.
            await Task.Delay(50, cancellationToken);

            _logger.LogInformation(
                "Order {OrderId} created successfully", orderId);

            return true;
        }
        catch (OperationCanceledException)
            when (cancellationToken.IsCancellationRequested)
        {
            _logger.LogInformation(
                "Order creation cancelled for {OrderId}", orderId);

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                ex,
                "Order creation failed for {OrderId}", orderId);

            throw;
        }
    }
}

This example demonstrates structured properties, cancellation handling, and exception logging. In a larger system, ensure that exception logging is owned by a clear layer to avoid duplicate logs.

9.3 Production-oriented example: ASP.NET Core 9 API

The following example shows a small API using built-in logging and a service. It is illustrative; replace the in-memory operation with actual persistence and domain validation.

Program.cs

using Microsoft.Extensions.Logging;

var builder = WebApplication.CreateBuilder(args);

// Keep the built-in providers that are appropriate for this app.
builder.Logging.ClearProviders();
builder.Logging.AddConsole();

builder.Services.AddScoped<OrderService>();

var app = builder.Build();

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        // Central exception handling should log once, with context.
        var logger = context.RequestServices
            .GetRequiredService<ILogger<Program>>();

        var exceptionFeature = context.Features
            .Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>();

        if (exceptionFeature?.Error is { } exception)
        {
            logger.LogError(
                exception,
                "Unhandled exception for request {TraceId}",
                context.TraceIdentifier);
        }

        context.Response.StatusCode =
            StatusCodes.Status500InternalServerError;
        context.Response.ContentType = "application/json";

        await context.Response.WriteAsJsonAsync(new
        {
            message = "An unexpected error occurred.",
            traceId = context.TraceIdentifier
        });
    });
});

app.MapPost("/orders/{orderId:int}", async (
    int orderId,
    OrderService service,
    CancellationToken cancellationToken) =>
{
    await service.CreateAsync(orderId, cancellationToken);
    return Results.Ok(new { message = "Order accepted", orderId });
});

app.Run();

public sealed class OrderService
{
    private readonly ILogger<OrderService> _logger;

    public OrderService(ILogger<OrderService> logger)
    {
        _logger = logger;
    }

    public Task CreateAsync(
        int orderId,
        CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        if (orderId <= 0)
        {
            _logger.LogWarning(
                "Rejected invalid order ID {OrderId}", orderId);

            throw new ArgumentOutOfRangeException(nameof(orderId));
        }

        _logger.LogInformation(
            "Order {OrderId} accepted for processing", orderId);

        return Task.CompletedTask;
    }
}

Important implementation notes

  • UseExceptionHandler should be configured early in the middleware pipeline so it can handle exceptions from later middleware and endpoints.
  • Do not return exception messages, stack traces, connection strings, or internal implementation details to clients.
  • The sample logs the unhandled exception centrally. Avoid logging the same exception at every layer.
  • The validation example throws an exception for simplicity. A real API would normally return a suitable 400 Bad Request response for invalid client input rather than treating it as an unexpected server failure.
  • The console provider is suitable for local development and container environments where a collector captures standard output. Production systems may require a centralized provider or agent.

9.4 Configure logging in appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "MyApp.Services": "Debug"
    }
  }
}

Meaning:

  • Default: Default minimum level for categories without a more specific rule.
  • Microsoft.AspNetCore: Reduce framework noise by requiring Warning or higher for matching categories.
  • MyApp.Services: Enable Debug and more severe events for that category prefix.

The most specific applicable category rule generally takes precedence. Provider-specific configuration may further affect what is emitted.

Environment-specific settings: appsettings.Development.json and other environment files can override settings when loaded by the default configuration system. Environment variables can also override configuration values.

9.5 Source-generated logging for hot paths

For frequently executed code, source-generated logging can reduce overhead and improve type safety.

using Microsoft.Extensions.Logging;

public static partial class OrderLog
{
    [LoggerMessage(
        EventId = 2001,
        Level = LogLevel.Information,
        Message = "Order {OrderId} created")]
    public static partial void OrderCreated(
        ILogger logger, int orderId);
}

Usage:

OrderLog.OrderCreated(_logger, orderId);

The containing type and method must be declared partial as shown. Source generation occurs during compilation. Use it where profiling or code conventions justify it; ordinary ILogger methods remain appropriate for most application code.

10. Recommended Folder Structure

MyApp/
├── Controllers/
│   └── OrdersController.cs
├── Services/
│   ├── IOrderService.cs
│   └── OrderService.cs
├── Middleware/
│   └── RequestLoggingMiddleware.cs
├── Models/
│   └── OrderRequest.cs
├── Configuration/
│   └── LoggingOptions.cs
├── appsettings.json
├── appsettings.Development.json
└── Program.cs

Logging does not require a dedicated folder. Keep logging close to the code that understands the event. Use a dedicated middleware or observability configuration class when it provides a clear responsibility. Avoid creating a generic logging wrapper that merely duplicates every ILogger method.

11. Execution Flow

Consider this statement:

_logger.LogInformation(
    "Order {OrderId} created", orderId);
  1. The method receives a message template and the value of orderId.
  2. The logging abstraction checks whether Information is enabled for the logger category.
  3. If enabled, the event is passed to configured providers.
  4. A provider formats or exports the event.
  5. The destination receives the event.
  6. A collector or logging system may index it for searching.

If the level is disabled, the system can avoid much of the work associated with emitting the event. However, expensive expressions evaluated before the logging call may still run.

For example, avoid building a large diagnostic string unnecessarily when Debug logging is disabled. For hot paths, use IsEnabled() checks or source-generated logging when justified.

12. Real Project Usage

IndustryExample eventsImportant considerations
E-commerceOrder creation, inventory reservation, payment failureUse order and trace identifiers; never log payment secrets
BankingTransfer state changes, authentication failures, audit-relevant actionsStrict access controls, integrity, retention, and regulatory requirements
HealthcareAppointment processing, integration failures, record-access eventsProtect patient information and follow applicable privacy rules
LogisticsShipment status changes, carrier API failures, delivery updatesCorrelate events across services and external providers
Social mediaUpload processing, moderation workflow failures, feed generation errorsHigh volume, privacy, and abuse monitoring
Enterprise softwareBackground jobs, imports, identity integration, report failuresSearchable context, consistent categories, operational alerts

Logging is useful across all these industries, but application logs are not automatically a compliant audit trail. Where an audit trail is required, implement the necessary integrity, access, retention, and review controls explicitly.

13. Performance Considerations

Memory

  • High-volume logs can allocate strings and structured property objects.
  • Large exception payloads increase storage and processing costs.
  • Buffering providers may retain entries in memory temporarily.
  • Avoid logging entire request bodies or large objects.

CPU

  • Formatting, serialization, enrichment, and network export consume CPU.
  • Debug and Trace logging can become expensive in frequently executed code.
  • Prefer message templates over string interpolation.
  • Use source-generated logging for measured hot paths.

Scalability

  • A synchronous or slow destination can create latency if a provider performs blocking work.
  • Centralized collectors should handle backpressure and outages safely.
  • High-cardinality properties can make indexing expensive.
  • Log volume grows quickly with request rate and retention duration.

Optimization checklist

  1. Set appropriate minimum log levels.
  2. Log meaningful events rather than every statement.
  3. Use structured message templates.
  4. Avoid expensive work when a level is disabled.
  5. Consider source-generated logging for hot paths.
  6. Keep payloads small.
  7. Sample repetitive high-volume diagnostics where appropriate.
  8. Monitor dropped events, queue saturation, and exporter failures.
  9. Set retention policies.
  10. Test behavior when the log destination is unavailable.

14. Security Considerations

Common risks

  • Logging passwords, access tokens, API keys, or connection strings.
  • Logging full payment details or unnecessary personal information.
  • Allowing untrusted input to forge misleading log lines.
  • Giving too many people access to logs.
  • Keeping logs indefinitely.
  • Returning internal exception details to API clients.
  • Treating ordinary application logs as tamper-proof audit evidence.

Best practices

  • Never log credentials, secrets, or authentication tokens.
  • Minimize personal and sensitive information.
  • Sanitize untrusted values when required by the output format and logging system.
  • Use access controls and encryption for stored and transmitted logs.
  • Define retention and deletion policies.
  • Restrict production log access and audit that access where appropriate.
  • Return generic error responses to clients and keep diagnostic details in protected logs.
  • Use stable identifiers rather than copying full request payloads.
  • Keep security events useful without exposing exploitable details.
  • Validate that log exports and dashboards do not leak secrets.

Warning: A log entry can be copied to multiple systems. Treat logging as a data-handling decision, not as a harmless debugging action.

15. Ten Common Beginner Mistakes


                 \# Mistake               Why it happens   Fix

                  1 Using                 It is easy to    Use `ILogger<T>`
                    `Console.WriteLine`   start with       for configurable
                    throughout the app                     logging

                  2 Logging everything at Severity is      Choose levels based
                    Error                 misunderstood    on operational
                                                           impact

                  3 Using string          It feels         Use structured
                    interpolation         familiar         message templates

                  4 Logging only          The message      Pass the exception
                    `ex.Message`          looks sufficient object when
                                                           appropriate

                  5 Catching and          The developer    Handle
                    swallowing exceptions wants to avoid a intentionally or
                                          crash            rethrow

                  6 Logging the same      Each layer wants Establish a clear
                    exception at every    to add context   owner for exception
                    layer                                  logging

                  7 Logging passwords or  Developers want  Redact and minimize
                    tokens                full diagnostic  sensitive values
                                          data             

                  8 Enabling Debug logs   More data seems  Configure
                    everywhere in         better           category-specific
                    production                             levels

                  9 Assuming console logs Output appears   Configure
                    are permanent         in the terminal  collection,
                                                           retention, and
                                                           storage

                 10 Using vague messages  Context is       Include safe
                    such as "Failed"      omitted          structured
                                                           identifiers and the
                                                           operation

16. Production Best Practices

  1. Inject ILogger<T> rather than constructing logging infrastructure in each class.
  2. Use meaningful log levels consistently across the application.
  3. Prefer structured logging with stable property names.
  4. Include useful context, such as an order ID or operation ID, when safe.
  5. Never log secrets such as passwords, tokens, or private keys.
  6. Avoid unnecessary personal data in messages and properties.
  7. Log exceptions with the exception object when the exception is relevant.
  8. Avoid duplicate exception logs across multiple layers.
  9. Use category-specific filters to control framework and application noise.
  10. Use scopes carefully to attach shared context to related events.
  11. Use event IDs for recurring events that benefit from stable identification.
  12. Keep messages actionable and explain the operation that failed.
  13. Use centralized collection for production systems that need cross-instance search.
  14. Set retention limits based on operational, legal, and business requirements.
  15. Monitor log pipeline health, including dropped events and exporter failures.
  16. Do not expose internal errors to clients.
  17. Correlate logs with traces where distributed tracing is available.
  18. Use metrics for counts and rates rather than relying on log searches for every measurement.
  19. Test logging configuration in each deployment environment.
  20. Use source-generated logging selectively in measured hot paths.
  21. Avoid excessive payloads and repetitive success logs.
  22. Review access permissions for log storage and dashboards.
  23. Document event naming conventions for teams.
  24. Test failure scenarios, including unavailable downstream services and cancellation.
  25. Keep logs truthful and precise; do not report success before the operation actually succeeds.

17. Interview Questions and Answers

Beginner Questions

1. What is logging in ASP.NET Core?

Logging records application events, warnings, errors, and other diagnostic information. It helps developers investigate failures and understand production behavior.

2. What is ILogger<T>?

It is a generic logging interface registered through the logging infrastructure. The generic type typically becomes the logger category, making it easier to filter messages by class or component.

3. What are the six standard log levels?

Trace, Debug, Information, Warning, Error, and Critical, ordered from least to most severe.

4. What is a logging provider?

A provider sends log events to a destination, such as the console, debug output, Windows Event Log, or a third-party logging platform.

5. Why is ILogger<T> preferred over Console.WriteLine?

It supports levels, filtering, categories, structured properties, and multiple destinations through configuration. Console.WriteLine alone does not provide the same logging abstraction.

6. What is a logging category?

A category identifies the source of a log. With ILogger<T>, it normally corresponds to the type's name.

7. What does LogInformation() do?

It writes an Information-level event when that level is enabled for the category and provider configuration.

8. When should LogWarning() be used?

Use it for unexpected or potentially problematic conditions that do not necessarily mean the current operation has failed permanently, such as a retry after a temporary failure.

9. When should LogError() be used?

Use it when an operation fails and the failure needs investigation or action. Include an exception when one is available and relevant.

10. Where can logging levels be configured?

They can be configured in appsettings.json, environment-specific settings, environment variables, code, and provider-specific configuration.

Intermediate Questions

11. What is structured logging?

Structured logging preserves named properties separately from the rendered message. For example, "Order {OrderId} created" allows a provider to index OrderId as a field.

12. Why is string interpolation less suitable for structured logging?

Interpolation constructs a string before the logger receives it, losing the original template-property structure. Message templates preserve the values as named fields for compatible providers.

13. What is a logging scope?

A scope attaches shared contextual data to log entries produced within a logical operation. It is useful for request or operation correlation, provided the provider supports and emits scopes.

14. How do you log an exception correctly?

Use an overload that accepts the exception object, for example _logger.LogError(ex, "Failed for order {OrderId}", orderId). This allows providers to capture exception details and the stack trace.

15. How does category-specific filtering work?

Configuration can specify a default minimum level and more specific rules for categories or namespaces. The most specific applicable rule generally takes precedence; provider-specific rules may also apply.

16. Should every exception be logged where it is caught?

No. Log at the layer that has the right context and responsibility. Logging and rethrowing the same exception at every layer creates duplicate noise.

17. What is the difference between logging and auditing?

Operational logging helps diagnose application behavior. An audit trail records security- or business-significant actions under explicit integrity, access, and retention requirements. Ordinary logs are not automatically compliant audit records.

18. How do you avoid logging sensitive information?

Use allowlisted fields, redact sensitive values, avoid request-body dumps, restrict log access, and test that credentials and personal data do not appear in output.

19. What is the role of logging in exception middleware?

Exception middleware provides a central place to handle otherwise unhandled exceptions, log diagnostic details, and return a consistent response without revealing internals to the client.

20. Why are log levels important in production?

They control noise, cost, and diagnostic detail. Appropriate filtering keeps important warnings and errors visible while avoiding excessive CPU, storage, and indexing costs.

Advanced Questions

21. How can logging affect application performance?

Message formatting, allocations, serialization, network I/O, and high log volume consume resources. Use sensible levels, structured templates, bounded payloads, and source-generated logging where profiling justifies it.

22. What is source-generated logging?

It uses the LoggerMessage source generator to generate efficient logging code at compile time. It can reduce runtime overhead and improve type safety, particularly on hot paths.

23. What is the difference between logs, metrics, and traces?

Logs describe events, metrics aggregate numerical measurements, and traces show the path and timing of work across components. Together they provide stronger observability than any one signal alone.

24. How would you correlate logs across microservices?

Propagate trace context using supported distributed tracing standards and instrumentation. Include trace or operation identifiers in logs, and ensure each service preserves the incoming context when making downstream calls.

25. What happens when a log provider is unavailable?

Behavior depends on the provider. It may buffer, retry, block, drop events, or fail in another way. Production systems should understand this behavior, monitor exporter health, and avoid allowing logging failures to destabilize core business operations.

26. Why can high-cardinality properties be expensive?

Properties with many unique values---such as a unique identifier for every event---can increase index size and query cost in some logging systems. Use them when they provide real diagnostic value and understand the storage platform's indexing behavior.

27. How would you design logging for a high-throughput API?

Use structured events, category-specific filtering, source-generated logging on measured hot paths, bounded data, sampling for repetitive diagnostics where appropriate, asynchronous collection when supported, and monitoring of dropped events and exporter health.

28. Why should exception details not be returned to clients?

Stack traces, internal paths, SQL details, and provider messages can disclose implementation details or secrets. Return a generic error response with a trace identifier and keep protected diagnostic information in server-side logs.

29. How do you handle duplicate logs in a layered application?

Define which layer owns logging for each failure type. Lower layers may add context and propagate the exception, while a boundary such as exception middleware logs unhandled failures. Avoid logging and rethrowing at every layer without a clear reason.

30. How would you investigate a production issue using logs?

Start with the approximate time and affected operation. Search by trace or correlation ID and safe business identifiers. Follow events across components, inspect exception details and dependency failures, compare with metrics and traces, and confirm the root cause before changing the system.

18. Hands-on Exercise

Exercise: Add useful logs to an order service

Goal: Practice log levels, structured properties, and exception logging.

Create an ASP.NET Core Web API project and implement an OrderService that:

  1. Accepts an order ID.
  2. Logs that processing has started.
  3. Rejects an invalid ID.
  4. Logs successful processing.
  5. Logs an exception if an unexpected failure occurs.
  6. Uses appsettings.json to configure the minimum log level.

Starter method:

public async Task ProcessAsync(
    int orderId,
    CancellationToken cancellationToken)
{
    // TODO: Log processing start.
    // TODO: Validate orderId.
    // TODO: Simulate asynchronous work.
    // TODO: Log successful completion.
    // TODO: Log unexpected exceptions appropriately.
    await Task.Delay(100, cancellationToken);
}

Acceptance criteria

  • Use ILogger<OrderService>.
  • Use named template properties such as {OrderId}.
  • Use Information for normal milestones and Warning for invalid or recoverable conditions.
  • Do not swallow exceptions.
  • Do not log secrets.
  • Verify that changing the configured level changes which messages appear.

19. Mini Project: Order Processing Diagnostics API

Objective

Build a small API that demonstrates production-oriented logging for order processing.

Features

  • POST /orders/{id} to submit an order.
  • GET /orders/{id} to retrieve an order's current status.
  • An injected service that logs processing milestones.
  • Structured log properties for order identifiers and operation names.
  • Consistent exception handling.
  • Configurable log levels.
  • A trace identifier in error responses.
  • Unit tests that verify the service's business behavior.

Suggested design

OrderDiagnosticsApi/
├── Controllers/
│   └── OrdersController.cs
├── Services/
│   ├── IOrderService.cs
│   └── OrderService.cs
├── Models/
│   └── OrderResponse.cs
├── Middleware/
│   └── ExceptionHandlingMiddleware.cs
├── appsettings.json
├── appsettings.Development.json
└── Program.cs

Example event sequence

Stretch goals

  • Add a correlation scope.
  • Add event IDs for important events.
  • Add a test ensuring secrets are not written to logs.
  • Configure a centralized logging provider.
  • Add metrics for successful and failed order processing.

20. Quiz: Multiple-Choice Questions

Question 1

Which interface is commonly injected for logging in ASP.NET Core?

A. IConsoleWriter
B. ILogger<T>
C. ILogDatabase
D. IErrorHandler

Correct answer: B. ILogger<T>

Explanation: The generic logger uses the type as its category and integrates with the configured logging infrastructure.

Question 2

Which level is generally appropriate for an unexpected condition that may recover?

A. Trace
B. Information
C. Warning
D. Critical

Correct answer: C. Warning

Explanation: Warning highlights a potentially problematic situation that does not always represent a failed operation.

Question 3

Which statement preserves structured properties?

A. _logger.LogInformation($"Order {id} created");
B. _logger.LogInformation("Order {OrderId} created", id);
C. Console.WriteLine(id);
D. throw new Exception(id.ToString());

Correct answer: B

Explanation: The named placeholder and corresponding argument preserve structured data for compatible providers.

Question 4

What is a logging provider responsible for?

A. Compiling C# code
B. Selecting database tables
C. Sending or writing log events to a destination
D. Handling every business exception automatically

Correct answer: C

Explanation: Providers connect the logging abstraction to destinations such as the console or a centralized logging system.

Question 5

What should usually be passed when logging an exception?

A. Only the exception message
B. The exception object
C. The user's password
D. The entire HTTP request body

Correct answer: B

Explanation: Passing the exception object lets compatible providers capture details such as the exception type and stack trace.

Question 6

What does ILogger<OrderService> normally use as its category?

A. The current URL
B. The database name
C. The OrderService type name
D. The log level

Correct answer: C

Explanation: The generic type typically determines the logger category, allowing component-specific filtering.

Question 7

Which item should never be written to ordinary application logs?

A. A safe operation name
B. A non-sensitive order identifier
C. An access token
D. A warning event

Correct answer: C

Explanation: Tokens and other credentials can grant access to systems and must not be exposed through logs.

Question 8

What is the primary purpose of a logging scope?

A. To create a database transaction
B. To attach shared context to related log entries
C. To automatically retry all failed operations
D. To suppress every exception

Correct answer: B

Explanation: Scopes can attach shared values to events during a logical operation when supported by the provider.

Question 9

Which signal is best suited to show request latency percentiles across an API?

A. Metrics
B. A single Error log
C. A source file name
D. A stack trace alone

Correct answer: A

Explanation: Metrics summarize numerical measurements and are well suited to latency distributions and trends. Logs and traces provide complementary details.

Question 10

What is a sensible strategy for unhandled exceptions in an API?

A. Return the stack trace to every client
B. Ignore every exception
C. Handle them centrally, log protected diagnostic details, and return a safe response
D. Log passwords to make debugging easier

Correct answer: C

Explanation: Centralized exception handling gives consistent responses and diagnostic logging while avoiding disclosure of internal details.

21. Summary

One-minute revision

  • Logging records meaningful application events.
  • ILogger<T> provides category-aware logging through dependency injection.
  • The six levels are Trace, Debug, Information, Warning, Error, and Critical.
  • Providers decide where log events go.
  • Structured logging preserves named values.
  • Scopes add shared context.
  • Pass exception objects when logging relevant failures.
  • Filter logs appropriately and never log secrets.
  • Production observability combines logs, metrics, and traces.

Five-minute revision

  1. Inject ILogger<T> into services and other components.
  2. Use Information for important normal milestones, Warning for concerning conditions, and Error for failed operations.
  3. Use message templates such as "Order {OrderId} created" rather than string interpolation.
  4. Configure minimum levels through configuration.
  5. Use scopes and trace identifiers to correlate related events.
  6. Log unhandled exceptions at a clear boundary and avoid duplicate records.
  7. Protect log data with access controls, minimization, and retention policies.
  8. Use centralized collection when production troubleshooting requires cross-instance search.
  9. Watch logging overhead, storage volume, and exporter health.
  10. Use logs alongside metrics and distributed traces.

Bullet-point summary

  • Logging helps explain application behavior after an event occurs.
  • Categories identify the component producing an event.
  • Providers route entries to configured destinations.
  • Filtering controls the amount of information emitted.
  • Structured fields make logs easier to query.
  • Exception details belong in protected diagnostic systems, not client responses.
  • Logging is essential to operations but does not replace testing, monitoring, or auditing.

Memory tricks

  • T-D-I-W-E-C: Trace, Debug, Information, Warning, Error, Critical.
  • Logs = events; Metrics = numbers; Traces = journeys.
  • Template + values = structured log.
  • Exception object + context = useful failure record.
  • Never log secrets.

Flashcards

FrontBack
What does ILogger<T> provide?Category-aware logging through dependency injection
What is a provider?A component that writes or exports log events
What is structured logging?Logging that preserves named properties separately from message text
What is a scope?Shared context attached to related log entries
Which level is used for failures?Usually Error for failed operations
What are logs best for?Understanding what happened in an operation
What are metrics best for?Counts, rates, durations, and trends
What must never be logged?Credentials, tokens, and unnecessary sensitive data

22. Cheat Sheet

NeedExample
Inject loggerILogger<OrderService>
Detailed diagnostics_logger.LogDebug("Cache key {Key}", key);
Normal milestone_logger.LogInformation("Order {OrderId} created", id);
Recoverable issue_logger.LogWarning("Retrying order {OrderId}", id);
Log exception_logger.LogError(ex, "Order {OrderId} failed", id);
Shared context_logger.BeginScope("Order {OrderId}", id)
Configure default level"Default": "Information"
Reduce framework noise"Microsoft.AspNetCore": "Warning"
Correlate requestsUse trace context or a safe request identifier
Protect dataRedact secrets and minimize personal information

Example configuration:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

23. Comparison Table

Logging vs debugging vs monitoring

ConceptPurposeTypical tools or techniques
LoggingRecord selected eventsILogger, providers
DebuggingInspect execution interactivelyBreakpoints, debugger
MonitoringDetect and report system conditionsMetrics, dashboards, alerts
Distributed tracingFollow work across servicesTrace IDs, spans, instrumentation
AuditingPreserve evidence of significant actionsControlled audit records and policies

Console.WriteLine vs ILogger

Console.WriteLineILogger
Writes plain text to console outputSupports levels and categories
No standard structured fieldsSupports structured message templates
Limited filtering by itselfIntegrates with configurable filters
Direct output destinationCan route through multiple providers

Logging vs exception handling

LoggingException handling
Records an eventDetermines how execution responds to an exception
Helps diagnose the eventCan recover, translate, or terminate the operation
Does not automatically recoverMay change the outcome or response
Can be used without exceptionsApplies when an exception or failure condition is handled

24. Key Takeaways

  • Use ILogger<T> instead of scattering Console.WriteLine through application code.
  • Select log levels according to operational meaning.
  • Prefer structured templates and safe contextual properties.
  • Log exceptions at an intentional boundary.
  • Configure categories and levels for each environment.
  • Protect logs as potentially sensitive data.
  • Use centralized collection, retention policies, and health monitoring in production.
  • Combine logs with metrics and traces for effective troubleshooting.

25. Revision Checklist

  • I can explain why logging is needed.
  • I know the six standard log levels.
  • I understand ILogger<T> and categories.
  • I can explain the purpose of a logging provider.
  • I can write a structured log message.
  • I understand scopes and event IDs.
  • I can configure log levels in appsettings.json.
  • I can log exceptions without exposing details to clients.
  • I understand the performance cost of excessive logging.
  • I know how to avoid logging secrets and unnecessary personal data.
  • I can distinguish logs, metrics, traces, and audit records.
  • I have completed the hands-on exercise or mini project.

26. Further Reading

Continue with these related roadmap topics on Logic Lense:

  • Configuration & appsettings.json
  • Dependency Injection
  • Middleware in ASP.NET Core
  • Exception Handling in ASP.NET Core
  • ASP.NET Core MVC
  • REST API Development
  • Health Checks
  • Distributed Systems and Microservices

Last updated 10/18/2026

Your notes

Sign in to save personal notes on this topic — they'll sync across your devices.

Was this tutorial helpful?

Help us create more free learning resources. Learn more

Make a Donation