How to Set Up Structured Logging That Helps You Debug Faster

It is 2 a.m., a customer reports a failed checkout, and the answer is hiding somewhere in 40,000 lines of plain-text logs. You search for “error”, get 3,000 matches, and start reading line by line. Most teams decide to set up structured logging right after an incident like that. Instead of sentences written for human eyes, every log line becomes a record with named fields you can search, filter, and group. The change is mostly about format, not tools, and a small team can make it in an afternoon.

What Structured Logging Actually Means

A structured log line is one event, written as data. A typical line looks like this:

{"level":"error","time":"2026-12-02T04:58:00Z","service":"checkout","event":"payment_failed","order_id":"8421","user_id":"9912","amount_cents":4999,"error":"card_declined","duration_ms":312}

Compare that with the plain-text version: “Payment failed for order 8421, user 9912, card declined after 312 ms.” A human reads both fine. A machine can only query the first one. With named fields, you can ask for every payment failure for one user in the last hour, or count failures by error type, without writing a new parser for each sentence shape. That is the whole idea behind the structured logging format: the log line is data first, and readable text second.

This also changes how you think about logs. They stop being a pile of text and start behaving like a small database you can query. Logs are one of the three pillars of observability, next to metrics and traces, and structured fields are what let you move between the three: the same request ID shows up in a log line, a metric label, and a trace span. If you want the wider picture first, read our guide to what observability covers and how logs fit in.

How to Set Up Structured Logging in Four Steps

You do not need to buy a platform or rewrite your app to get started. The four steps below take a typical web service from plain text to structured logs, and each step is small enough to ship on its own.

1. Pick a format and stick to it

JSON is the default choice for a reason: every language can produce it, every log tool can read it, and one JSON object per line keeps each event separate. A consistent json log format also means your searches work the same way in development and production. If your stack already writes logs in another structured form, such as logfmt, that works too. What matters is that the whole team uses one format, so nobody has to guess how a line is shaped.

function log(level, event, fields = {}) {
  const line = { level, event, time: new Date().toISOString(), service: "checkout", ...fields };
  process.stdout.write(JSON.stringify(line) + "n");
}
log("info", "order_created", { order_id: "8421", user_id: "9912" });

The helper above is enough to start. A logging library adds rotation, sampling, and async writes later, but decide the format first: changing formats after six months of logs is the painful part.

2. Decide which fields every log line carries

Agree on a short list of fields that appear in every line, then add event-specific fields only where they help:

Field What it holds Example
level How serious the event is error
time UTC timestamp in ISO 8601 2026-12-02T04:58:00Z
service Name of the service writing the line checkout
event Short machine-readable name payment_failed
request_id ID that ties one request together req_9f31ac
duration_ms How long the work took 312

Keep the list short. Ten fields you always fill beat thirty fields that are half empty. Event-specific detail, such as order_id or the payment provider, goes in extra fields on the lines that need them.

3. Add correlation IDs to follow one request

A single user action often touches three services, and without a shared ID you cannot connect the log lines. Generate a request ID at the edge, pass it along in a header, and include it in every log line that request produces. When a customer reports a problem, you search for one ID instead of guessing timestamps across services. Give each background job run its own ID the same way.

4. Send logs somewhere you can search them

Logs written to a file on one server help nobody during an incident. Send them to a central place where the whole team can search by field. For a small setup, shipping JSON lines to Loki with Grafana for searching keeps costs low, and our walkthrough of running Loki and Grafana on a small budget covers the setup. When you outgrow that, compare the options in our roundup of log management tools for small teams before paying for a hosted platform.

Log Levels That Stay Useful

Five levels cover almost every case. The rule that keeps them honest: ERROR means something broke and a human should look at it soon. If half your lines are ERROR, the level means nothing, and the real failures hide in the noise.

  • DEBUG: detail for local development, off in production.
  • INFO: normal events worth keeping, such as orders created.
  • WARN: something odd that fixed itself, such as a retry that worked.
  • ERROR: a request failed or a feature broke.
  • FATAL: the process cannot continue.

Log at the level where you know what happened, not where the error surfaces three layers up. A database timeout logged as ERROR in the handler, the service layer, and the controller gives you three lines for one failure.

Debugging With Structured Logs: A Real Example

Say failed checkouts spike on a Tuesday morning. With plain text you would grep, skim, and guess. With structured logs the work looks like this. First, filter to event=payment_failed for the last hour and group by the error field. The count shows card_declined jumping from a handful per hour to several hundred, while other errors stay flat. Next, filter those lines by provider and see the spike comes from one payment provider only. Then group by duration_ms and notice the failures answer in under 50 ms, which points at the provider rejecting requests early rather than your code timing out. Three filters, no reading of raw lines, and you know where to look next. When the problem sits outside your own code, the same habit helps: our guide to debugging production issues without SSH access walks through tracing a fault from the outside in.

Slow requests work the same way. Filter to one endpoint, sort by duration_ms, and read the slowest lines first. The fields tell you which user, which plan, and which database query sat behind each slow request. A stack trace still matters for the exact line of code, so pair the log line with the trace, as explained in our guide to reading a stack trace.

Mistakes That Undo the Whole Effort

  • Hiding sentences inside JSON. A line with one message field holding a full sentence is plain text wearing a JSON costume. Put the facts in fields.
  • Logging secrets. Passwords, API tokens, session cookies, and full card numbers never belong in logs. Scrub them at the logging call, not in the log pipeline, so a misconfigured shipper cannot leak them.
  • Logging everything at DEBUG in production. Volume hides the lines that matter and fills your disk. Keep DEBUG for local runs and short troubleshooting windows.
  • Renaming fields between services. userId in one service and user_id in another breaks every query that spans both. Agree on names once and write them down.
  • Storing local time. Timestamps in server-local time turn a cross-region incident into a timezone puzzle. Always log UTC in ISO 8601, and let the viewer convert it.

Frequently Asked Questions

Do I need a logging library, or can I print JSON myself?

Printing JSON yourself is fine for a small service, and the helper above shows how little code it takes. Move to a library when you need log rotation, sampling, or async writes, not before.

Should I keep plain-text logs for local development?

Yes. Pretty-print logs in development so they stay easy to read, and write JSON in staging and production. Keep the fields identical in both modes so the queries you practice locally work the same way live.

Will structured logging slow my app down?

Encoding JSON adds a small cost per request, and synchronous writes can block a request if the destination is slow. Write to stdout and let a separate shipper handle delivery, or use async writes, so a slow log pipeline never stalls your app.

Start with one service, not all of them. Give it a JSON format, a few fields that never change, and a request ID on every line. Use it for a week and run the payment-failure filter above on your own data. Once one service proves the habit, rolling it out to the rest is mostly copy and paste.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.