ASP.NET Core MVC Intermediate

Logging

Logs tell you what your app is doing in production, where you cannot attach a debugger. This lesson shows how to write logs with ILogger, how log levels and categories filter them, and why structured logging beats string concatenation.

The path of a log message
  1. StartYour code logs_logger.LogWarning("Stock low for {ProductId}", id)
  2. Step 2Category and level checkedCategory OrdersController, level Warning
  3. Step 3Filters appliedMinimum levels from the Logging section of configuration
  4. Step 4Providers write itConsole, Debug, Event Source, or a cloud provider
  5. EndYou read itTerminal, log files, Application Insights, OpenTelemetry tools

The idea in plain words

Ask for an ILogger<T> in any class and call methods like LogInformation or LogError. T becomes the log category, usually the class name, so you can tell where a message came from and filter by it. Each message has a level, and configuration decides the minimum level written for each category.

Use message templates with named placeholders instead of string interpolation. Providers that support structured logging store the values as separate fields, so you can search for every log with a given ProductId.

  • Trace and Debug: detailed diagnostics, usually off in production.
  • Information: normal events, such as an order being placed.
  • Warning: something unexpected that the app handled.
  • Error: an operation failed. Critical: the app is in serious trouble.

Example

C#
public class OrdersController : Controller
{
    private readonly ILogger<OrdersController> _logger;

    public OrdersController(ILogger<OrdersController> logger) => _logger = logger;

    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> Place(OrderModel model)
    {
        _logger.LogInformation("Placing order for {CustomerId} with {ItemCount} items",
            model.CustomerId, model.Items.Count);
        try
        {
            await _orders.PlaceAsync(model);
            return RedirectToAction("Done");
        }
        catch (PaymentException ex)
        {
            _logger.LogError(ex, "Payment failed for {CustomerId}", model.CustomerId);
            ModelState.AddModelError("", "Payment failed, please try again.");
            return View(model);
        }
    }
}

Example: filtering in appsettings.json

JSON
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}

Common mistakes

  • Building messages with $"..." interpolation, which loses structure and costs time even when the level is off.
  • Logging passwords, tokens or full personal data.
  • Catching an exception and logging only ex.Message; pass the exception itself so the stack trace is kept.
  • Leaving Debug level on in production and filling disks with logs.

Interview question

Why should you use message templates instead of string interpolation in ASP.NET Core logging?

With a template like "Order {OrderId} failed", the logger keeps OrderId as a named property, so structured logging providers can index and query it, and the message is only formatted if the level is enabled. Interpolation builds the final string up front, losing the structured values and wasting work when the log level is filtered out.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.