Module 2: Structured Logging (The Digital Evidence)
📚 Module 2: Structured Logging
Course ID: DOTNET-802
Subject: The Digital Evidence
Beginners use Console.WriteLine or plain text logs. Seniors use Structured Logging (Serilog). This turns your logs into a searchable database instead of a messy text file.
🏗️ Step 1: The “Messy Text” Problem
Imagine you have 1 million logs that look like this: [2024-04-21] INFO: User Alice logged in from IP 1.2.3.4
The Problem: You want to find every user who logged in from that IP. You have to use “Grep” or complex text searching. It’s slow and error-prone.
🏗️ Step 2: The Structured Solution (JSON)
In Structured Logging, we save logs as Objects.
🧩 The Analogy: The Spreadsheet vs. The Diary
- Plain Text Log: Like a Diary. You have to read every page to find a specific event.
- Structured Log: Like a Spreadsheet. You can instantly filter the “IP” column to see all matching rows.
In Code (Serilog):
// Instead of this:
Log.Information("User {UserName} logged in from {IP}", "Alice", "1.2.3.4");
// It is saved like this:
{
"Timestamp": "2024-04-21",
"Level": "Information",
"UserName": "Alice",
"IP": "1.2.3.4"
}🏗️ Step 3: Why do we use it?
- Dashboards: You can build a chart in Grafana or Kibana showing “Logins per Hour” instantly.
- Alerting: You can set an alarm: “If I see 50 Failed Logins for the SAME user in 1 minute, send me a Slack message!”
🥅 Module 2 Review
- Plain Log: Just text. Good for humans, bad for computers.
- Structured Log: Data objects (JSON). Good for both!
- Serilog: The standard library for structured logging in .NET.