Skip to main content

Logging

Think of logging in 3 layers:

ILogger (abstraction)
→ Configuration (levels + filters)
→ Providers (Console / Serilog / Cloud)

What is Logging? (One-liner)

Logging records what the application is doing at runtime for monitoring, debugging, and diagnostics.

Used for:

  • Debugging errors
  • Tracking user actions
  • Monitoring production systems
  • Auditing & performance analysis

ILogger — The Core Concept ⭐

What ILogger is

ILogger is an abstraction for writing log messages, independent of the logging provider.

Why this matters:

  • Swap providers without changing code
  • Works in all environments
  • Integrated with DI

Getting ILogger (DI)

public class PersonsController : Controller
{
private readonly ILogger<PersonsController> _logger;

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

📌 Interview sentence:

"ILogger<T> uses the class name as the logging category."


Log Levels (MEMORIZE THIS ORDER)

Trace
Debug
Information
Warning
Error
Critical

How to explain in interviews

  • Trace / Debug → Development only
  • Information → Normal flow
  • Warning → Something looks off
  • Error → Operation failed
  • Critical → App is broken

Example

_logger.LogInformation("User {UserId} logged in", userId);
_logger.LogWarning("Login attempt failed for {UserId}", userId);
_logger.LogError(ex, "Unexpected error while saving data");

Structured Logging (VERY IMPORTANT ⭐)

Bad (plain text)

_logger.LogInformation("User John logged in");

Good (structured)

_logger.LogInformation("User {UserName} logged in", user.UserName);

Why?

  • Searchable
  • Filterable
  • Query-friendly (Seq, ELK)

📌 Interview sentence:

"Structured logging stores data as key-value pairs instead of raw strings."


Logging Configuration (appsettings.json)

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

How to explain

  • Default = Information
  • ASP.NET Core noise reduced to Warning
  • Environment-specific overrides allowed

📌 Common follow-up:

"We log more in Development, less in Production."


Logging Providers

Built-in Providers

  • Console
  • Debug
  • EventSource
  • EventLog (Windows)

Third-party (Real World)

  • Serilog ⭐⭐⭐
  • NLog
  • log4net

📌 Interview answer:

"Serilog is popular because of its structured logging and flexible sinks."


Serilog (Production-Grade Logging)

Why Serilog?

  • Structured logging first
  • Rich ecosystem
  • Many sinks

Common sinks

  • Console
  • File
  • Seq
  • Database
  • Cloud (Azure, AWS)

Program.cs Setup (Recognize This)

builder.Host.UseSerilog((ctx, services, config) =>
config.ReadFrom.Configuration(ctx.Configuration).ReadFrom.Services(services),
);

Logging with Serilog

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

Same ILogger API → Serilog underneath

No code change needed


HTTP Logging (Middleware Level)

Purpose

  • Log requests & responses
  • Debug APIs
  • Performance analysis

Enable HTTP logging

app.UseHttpLogging();

With Serilog (Better)

app.UseSerilogRequestLogging();

📌 Interview sentence:

"Request logging helps trace request lifecycles and latency."


9️⃣ Where Logging Happens

LayerLogging Usage
ControllerRequests, user actions
ServiceBusiness logic
MiddlewareRequests, errors
Exception handlingErrors

Best Practices (VERY IMPORTANT)

✅ Use structured logging ✅ Adjust log levels per environment ✅ Use centralized logging (Seq) ❌ Never log passwords / tokens ❌ Avoid excessive logging in hot paths ❌ Don't log exceptions twice


Common Interview Questions + Short Answers

Q: Why ILogger instead of Console.WriteLine?

ILogger supports log levels, structured data, providers, filtering, and production tooling.

Q: Why structured logging?

Easier searching, filtering, and analytics.

Q: What log level in production?

Information and above (Warning+ for framework logs).

Q: Serilog vs ILogger?

ILogger is the abstraction, Serilog is the provider.


One-Paragraph Interview Answer

"ASP.NET Core uses ILogger as an abstraction for logging, allowing us to plug in providers like Serilog without changing code. It supports multiple log levels and structured logging, which makes logs searchable and easier to analyze. Logging behavior is configured in appsettings.json and adjusted per environment. In production, we typically use Serilog with centralized sinks like Seq and enable HTTP request logging for observability."


If You Remember ONLY 6 Things

  1. ILogger = abstraction
  2. Log levels order matters
  3. Structured logging > plain text
  4. appsettings controls verbosity
  5. Serilog = production standard
  6. Never log sensitive data