SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
  • Three Pillars of Observability
  • Logging Best Practices
  • Log Aggregation
  • Metrics and Instrumentation
  • Distributed Tracing
  • Alerts and Monitoring
  • Dashboards and Runbooks
  • SLOs and Error Budgets
  • Incident Management and Postmortems
  • Profiling
  • Audit Logs
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Operations and Security/Observability

Logging Best Practices

What to log, how to structure it, and what to never write down.

⏱ 12 min readBeginnerHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A log is a line your program writes to say "this just happened". Logging best practices are the habits that make those lines useful when something breaks, and safe to keep.

  • Use levels (DEBUG, INFO, WARN, ERROR) so you can turn the volume up or down.
  • Write structured logs (JSON with named fields), not only free text, so machines can search them.
  • Put a request ID in every line to follow one request, and never log secrets or personal data.

02Concept: What is it?

Logs are the diary of your program. When a customer says "my order failed at 10:05", the log is often the only record of what really happened. But a diary full of noise, or one that contains passwords, is worse than no diary. Good logging is a small set of habits.

Every log line should answer: when (timestamp, ideally in UTC), how serious (level), who wrote it (service, version, host), what happened (a clear message) and in what context (request ID, user ID, order ID and other fields).

Plain text and structured logs
Plain text
📝10:00:12 ERROR payment: card declined for order 42
↓search by text pattern
😓Fragilewording changes break searches
Structured (JSON)
🧱{"level":"ERROR","service":"payment","order":42,"req":"r-102"}
↓filter by field
✅Searchablelevel = ERROR and req = r-102
Both say the same thing, but the structured line can be filtered by any field without guessing a pattern.
🧠Log for the person who is paged at 3 a.m.
That person does not know your code. Each line should make sense on its own, without needing to read the source.

03Real-Life Example

🍵The Ship's Logbook
A ship's captain keeps a logbook. Each entry has the time, the position, the weather and what happened. Entries are short and factual. Routine notes ("engine steady") go in one style and emergencies ("fire in the engine room") are marked clearly so they are easy to find. The captain never writes the safe combination in the logbook, because many people read it later. When another ship asks "what happened to flight 12 of your cargo?", the log carries a cargo number so entries can be found fast.
Ship's logbook
Application logs
Time and position on each entry
Timestamp, service and host on each line
Routine note vs emergency mark
Log level: INFO vs ERROR
Short, factual sentences
A clear message plus named fields
Cargo number on related entries
A request or trace ID on related lines
Never writing the safe combination
Never logging passwords, tokens or card numbers
A rule for how long to keep old books
A retention period for logs
One line, explained
🕐TimeUTC timestamp
🚦LevelERROR
🧩Whopayment v1.4.2
💬Whatcard declined
🔗Contextreq=r-102 order=42

04Why Do We Need It?

🔎Find the cause
Logs hold the exact error and context that charts cannot show.
🔗Follow one request
A request ID turns thousands of mixed lines into one clear story.
💰Control cost
Levels and sampling keep volume, and the bill, under control.
🔒Stay safe
Careful logging avoids leaking secrets and personal data into a place many people can read.
🤖Let tools help
Structured logs can be searched, counted and alerted on by machines.
🧾Prove what happened
Audit logs show who did what and when, which matters for security and law.
A log is only useful if you can find the right line, trust it, and safely keep it.

05Where Do We Use It?

🌐Request handling
Log the start, the outcome and the time taken of each request, with its request ID.
⚠️Errors and retries
Log failures with the error, the input that mattered, and what the code did next.
🔐Security events
Log logins, failed logins and permission changes in a separate audit log.
⚙️Background jobs
Log start, end, counts and failures, so a silent stop can be noticed.
🔌Calls to other systems
Log which service you called, how long it took and the result.
🚀Start-up and config
Log the version and key settings (not secrets) at start-up, so you know what is running.

06Types / Parts / How It Works

Log levels

LevelUse it forExample
DEBUGDetail for developers. Usually off in production.Loaded cart with 3 items
INFONormal, meaningful eventsOrder placed, total 42.50
WARNSomething odd that the system handled, but should be looked atSlow gateway reply (2300 ms), retrying
ERRORAn operation failed and needs attentionCard declined, order failed
FATAL / CRITICALThe process cannot continueCannot connect to the database, shutting down

What a good structured line looks like

One JSON log line
{"ts":"2026-12-03T10:00:08Z","level":"ERROR","service":"payment","version":"1.4.2",
 "req":"r-102","user":"u-52","msg":"Card declined","code":"insufficient_funds"}

What to log, and what to leave out

Safe and unsafe fields
Log these
🔗Request ID
👤User ID
⏱️Duration
🏷️Error code
Never log these
🔑Passwords
🎫Tokens, API keys
💳Full card numbers
📧Raw personal datamask or leave out
Safe and useful Dangerous
When in doubt, log an ID that lets you look the data up elsewhere, not the data itself.
VisualizerMake a noisy, leaky log into a good oneSwitch to structured JSON, raise the level, turn on masking and the request ID, then try to follow one request. Watch the size, the leaks and how easy it is to find one request.
Format
Lowest level kept
Try to follow one request
10:00:01 DEBUG gateway: Parsed request headers
10:00:02 INFO checkout: Order started user=u-17 email=ana@example.com
10:00:03 INFO checkout: Order started user=u-52 email=bo@example.com
10:00:04 DEBUG cart: Loaded cart items=3
10:00:05 DEBUG cart: Loaded cart items=1
10:00:06 INFO payment: Charging card card=4242424242424242 amount=42.50
10:00:07 WARN payment: Slow gateway reply ms=2300
10:00:08 ERROR payment: Card declined card=5555555555554444 code=insufficient_funds
10:00:09 DEBUG db: Query ok ms=12
10:00:10 INFO checkout: Order placed total=42.50
10:00:11 WARN checkout: Retry 1 of 3
10:00:12 ERROR checkout: Order failed reason=card_declined
Lines kept
12 / 12
at DEBUG and above
Size
659 B
this sample only
Lines leaking data
4
raw email or card
Lines of the followed request
-
pick a request
4 lines contain a raw email or card number. Logs are copied to many systems and kept for weeks, so personal data in them is a leak waiting to happen. Turn masking on.

Twelve made-up events from two checkout requests that overlap in time. Sizes are for this small sample only and only show the direction: more levels and more fields mean more bytes.

07How to Use It / Steps / Implementation

Habits for good logs

  1. 1
    Pick a log format for the whole team
    Use structured JSON with the same field names in every service (ts, level, service, req, msg).
  2. 2
    Use levels with care
    INFO for normal events, WARN for handled oddities, ERROR for failures. Do not log a normal, expected case as ERROR.
  3. 3
    Add a request ID at the edge
    Create it when the request enters, pass it in a header to every call, and add it to each log line automatically (with a logging context or middleware).
  4. 4
    Write messages that stand alone
    'Card declined for order 42 (insufficient_funds)' is better than 'error in handler'.
  5. 5
    Keep secrets and personal data out
    Mask or leave out passwords, tokens and card numbers. Add a filter that scrubs known fields as a safety net.
  6. 6
    Log once, at the right place
    Log an error where you handle it, not at every layer it passes through. Repeated lines for one failure make noise.
  7. 7
    Set the level per environment
    DEBUG in development, INFO in production, and a way to raise one service to DEBUG for a short time while you investigate.
  8. 8
    Mind the cost
    Avoid logging inside tight loops, and sample very frequent, low-value lines.
💡Log the decision, not just the event
"Retrying payment (attempt 2 of 3, reason timeout)" helps much more than "payment error", because it tells the reader what the code chose to do.
⚠️Logging must never break the app
Write logs asynchronously or through a buffer, and make sure a full disk or a slow log system cannot block your requests.

08Key Terms to Know

TermMeaning in easy words
Log levelA label for how serious a line is: DEBUG, INFO, WARN, ERROR
Structured loggingWriting logs as named fields (usually JSON) instead of only free text
Request / correlation IDA unique ID carried through a request, so its lines can be found together
ContextExtra fields such as user ID or order ID that explain a line
Audit logA protected record of who did what and when, kept for security and rules
PIIPersonally identifiable information, such as an email or a phone number
Masking / redactionHiding part or all of a sensitive value before it is logged
SamplingWriting only a share of very frequent lines
Log rotationStarting a new file when one is full or old, and removing the oldest
RetentionHow long logs are kept before they are deleted
Stack traceThe list of calls that led to an error, often printed with an exception

09Pros, Cons and Trade-offs

✅ Pros
  • Fast, precise answers to 'what happened?'
  • Structured logs can be searched and counted by any field
  • A request ID ties many services together
  • Levels let you tune detail and cost
  • Audit logs support security and compliance
⚠️ Cons
  • More logging means more storage, network and cost
  • Free-text logs are fragile to search
  • Easy to leak secrets or personal data by accident
  • Too many lines hide the important ones
  • Writing logs adds a little work to each request

Trade-offs

ChoiceWe gainWe lose
DEBUG in productionMaximum detail for an investigationA very large volume, higher cost and more risk of leaking data
INFO and aboveA calm, affordable logLess detail unless you raise the level
JSON logsSearchable by field, easy for toolsHarder for a person to read in a terminal
Plain text logsEasy to read by eyeFragile pattern matching, and fields are hard to filter
Log at every layerNever miss where it failedDuplicate lines and noise
Sample frequent linesMuch lower volumeYou may miss a rare event in the dropped part

10Common Problems and Mistakes

Common mistakes

  1. Logging secrets or personal data. A password or card number in a log is copied to many places and kept for weeks.
  2. No request ID. Lines of different requests are mixed, and you cannot rebuild one story.
  3. Everything at ERROR. If every line looks urgent, nothing is. Use levels honestly.
  4. Vague messages. "Something went wrong" helps no one at 3 a.m.
  5. Logging in a hot loop. A line per item in a loop of a million items can slow the service and flood storage.
  6. Logging the same error many times. Each layer logs it again, and one failure becomes ten lines.
  7. Local time and mixed time zones. Use UTC, so lines from different machines line up.

Things to watch

🌊Log floods
A failing dependency can make every request write errors. Rate-limit repeated lines.
💾Full disks
Without rotation a log file can fill the disk and take the service down.
🪪Privacy rules
Personal data in logs may be covered by laws, including rights to delete it.
🐢Slow logging
Synchronous writes to a remote system can slow every request. Buffer them.

11Real-World Examples

🧰Logging libraries
Most languages have a standard library or popular one (for example Log4j or SLF4J in Java, logging or structlog in Python, pino or winston in Node, zap in Go) that supports levels and JSON.
🐳Containers
A common pattern is to write logs to standard output and let the platform collect them.
🔐Audit trails
Banks and healthcare systems keep protected audit logs of who accessed which records.
🧯Incident response
Teams search logs by request ID to rebuild what one failing customer saw.
🧮Counting from logs
Some teams turn log lines into metrics, such as the number of ERROR lines per minute.
🕵️Security monitoring
Repeated failed login lines can feed alerts for attacks such as password guessing.
📝Note
Specific libraries and defaults change between versions. Check your language and framework docs for the current recommended setup.
Mini case: finding one customer's failure
☎️Customer reportsorder failed ~10:05
→↓find req ID
🔗req = r-102from the error page
→↓filter all services
📜6 lines, in orderdeclined, retry, failed
With a request ID the answer is one query, not an hour of reading.

12Related Topics to Read Next

Three Pillars of Observability→

Where logs fit next to metrics and traces.

Log Aggregation→

Where all those log lines go and how you search them.

Distributed Tracing→

Uses the same trace and request IDs that good logs carry.

Alerts and Monitoring→

Logs can feed alerts, such as a rise in ERROR lines.

Secrets Management→

Keeps secrets out of code and out of logs in the first place.

Data Formats→

JSON and other formats used for structured logs.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Levels: DEBUG (dev), INFO (normal), WARN (handled oddity), ERROR (failed).
  • ✔Format: structured JSON with the same field names everywhere.
  • ✔Always include: UTC time, level, service, message, request ID.
  • ✔Never log: passwords, tokens, card numbers, raw personal data.
  • ✔Log once: where the error is handled, not in every layer.
  • ✔Cost: INFO in production, sample hot lines, set retention and rotation.
  • ✔Safety: async writes, so logging never blocks a request.
  • ✔One line: “Log for the tired person at 3 a.m.: clear, structured, linked by ID, and free of secrets.”
← Previous
Three Pillars of Observability
Next →
Log Aggregation