How 7 Simple Logging Principles Made Me a Better Senior Developer
My first job was as a support engineer intern. All day, every day, I read logs that other developers wrote. Between the logs and dashboards, I chased one customer bug after another.
Some logs told me what broke within seconds. Others left me guessing for hours. The difference always came down to the team that built them.
A couple of years later, I moved into full-time development. Over time, I grew into a team lead and senior developer.
You would think those support years made me great at logging. They didn’t.
I still treated logs as the last thing to write. I cared about the feature. Logs? I’d throw them in at the very end, if I remembered.
Non-medium members click here to read for free.
That was the real problem, and it changed slowly. Every few months, a bad log burned me and taught me a new rule.
Here are simple principles I follow while writing logs in the projects.
1. Write Logs for Whoever Reads Them Next
Here’s the thing about a log line. You write it with the code wide open in front of you. Then someone reads it weeks later, and they’ve got nothing but that one line.
Maybe it’s a support engineer. Maybe it’s whoever is on call. Maybe it’s you, six months from now, with zero memory of this code. I used to write lines like this all the time:
ERROR Error in processPayment
ERROR Error in processPayment
Okay, something broke in payments. Which payment? How much? Why? No idea.
Now look at this one:
WARN Payment declined by gateway order_id=ord_123 amount=129.99 currency=EUR gateway_code=05 reason=do_not_honor
WARN Payment declined by gateway order_id=ord_123 amount=129.99 currency=EUR gateway_code=05 reason=do_not_honor
Whoever picks this up can reply to the customer right away. No digging through code.
So log what happened, plus the details that explain it.
Here’s my trick before I commit a line. Picture the newest person on your team reading it. Can they act on it without asking you anything? Then push it.
2. Stop Logging Everything Just in Case
You know that little worry about skipping the one line you’ll need later? I call it logging FOMO. It’s how we end up with a log line inside every loop and around every cache lookup.
Each line costs money to ship and store, but the higher cost is noise.
I learned this on a legacy system I had just inherited. A critical bug came in, so I opened the server’s log folder. It held more than a thousand files, each named by timestamp and each thousands of lines long.
Most of those lines looked like this:
Going into payment function
Payment function success
Failed with errors
Going into payment function
Payment function success
Failed with errors
These were leftovers from someone’s debugging session, never cleaned out. None said which order it was, what amount, or what the error even was.
Production kept writing them every day. Finding the one real failure in all of that took me hours.
Once the bug was fixed, I took two sprints to clean up the logging. Out went every leftover debug log, and most of the minor ones too.
I gave every line a proper timestamp. I set up log rotation too, so old files stopped piling up forever.
The rest got sorted into proper INFO and ERROR messages. At every key step, I pictured it failing. Whatever I’d need to know in that moment went into the log.
That cleanup changed how I think about volume. I don’t just log whatever comes to mind anymore. Here are the tools I lean on.
Sampling keeps a share of events. Deduplication squashes a thousand copies of one error into one entry plus a count.
Rate limits help too, but watch out. Cap things too hard, and the line you needed gets dropped.
Whichever you use, save a few real samples of every error type, plus how often it showed up.
For routine success, write one summary line or sample a small slice. Push step-by-step detail down to DEBUG.
Many teams keep DEBUG off in production by default. The real risks are volume and sensitive data. Some teams switch DEBUG on for one service during an investigation.
My rule of thumb for any new line is simple. If I can’t name who reads it and what they’d do about it, it’s gone. Or it moves to DEBUG.
3. Log the Decisions Your Code Makes
Code on the happy path needs little explaining. The weird bugs hide in the branches. Retries, fallbacks, skipped steps, feature flags.
Picture a flight search service in New York. The airline partner’s API stalls, so your code grabs fares from the cache.
Customers see stale prices. Your logs see nothing unusual, just a 200.
One line fixes that:
WARN Fares API timed out, serving cached fares route=JFK-LHR timeout_ms=3000 cache_age_s=1840
WARN Fares API timed out, serving cached fares route=JFK-LHR timeout_ms=3000 cache_age_s=1840
With retries, skip the warning on each try. I’d rather see one line at the end, like “3 tries, gave up” or “2 tries, worked.”
Circuit breakers get the same treatment. I want to know the moment it trips and the moment it lets traffic through again. The calls it turns away in between can stay quiet.
In code review, check every catch, else and fallback branch. Each one should make its behavior observable. For branches that run nonstop, use a metric or a trace span instead of a log line.
4. Attach the Context That Lets You Find One Request
Picture this. A customer in Paris says their food order never showed up. That order went through three services: orders, payments, and dispatch.
Each one logged something, and nothing links those lines together.
Two habits fix this for good. First up, structured logging. You stop writing log messages as sentences and start writing them as named fields.
# Examples use structlog, which accepts key-value fields
# Hard to query: the IDs are buried in a sentence
log.info(f"Order {order_id} assigned to courier {courier_id}")
# Easy to query: each value is its own field
log.info("order_assigned", order_id=order_id, courier_id=courier_id)
# Examples use structlog, which accepts key-value fields
# Hard to query: the IDs are buried in a sentence
log.info(f"Order {order_id} assigned to courier {courier_id}")
# Easy to query: each value is its own field
log.info("order_assigned", order_id=order_id, courier_id=courier_id)
Second, pass trace context between services. The W3C Trace Context standard gives you a traceparent header for it. OpenTelemetry uses that header too.
A bare trace ID gets you correlation and not much else. Every service has to forward it and print it in its logs, or you lose the thread.
Java has MDC, Python has contextvars, and Node.js has AsyncLocalStorage. Wire your logger or OpenTelemetry to read from them.
Here is the senior part. Ever heard someone say a field has high cardinality? They mean it has tons of possible values. Think of user IDs. You might have millions. HTTP methods? Maybe five.
High-cardinality fields like user_id are what isolate one failing customer. In logs, what they cost you comes down to what you index and how long you keep it.
Metrics don’t work like that. Add a user ID as a label, and each user gets a time series of their own. That bill grows fast. So I keep IDs in the logs and out of metric labels.
5. Make Every Log Level Mean Something
This principle is about what each level should trigger.
Picture a login service in Sydney that logs every wrong password as ERROR. Wrong passwords happen all the time, so the alert channel lights up nonstop. My bet? Within a week, somebody mutes it.
Then the database starts refusing connections. Its ERROR shows up in that same muted channel, and nobody sees it.
Someone typing the wrong password once? That’s normal. It’s not an application error. Fifty tries on one account in a minute, though, could be an attack. Track that pattern as its own security signal.
Levels only work as a written team convention. Here is the guide my team uses:
- ERROR: the operation failed and needs investigation.
- WARN: something unusual happened, but the system coped.
- INFO: a business event, like an order placed or a job finished.
- DEBUG: detail for troubleshooting, often off by default in production.
Keep levels and paging separate. Alert on symptoms users feel, such as error rate, latency or failed checkouts. CPU and memory belong on a dashboard for when you’re investigating.
My default for failures is simple. Log it once, in the place that deals with it. This breaks it:
catch (SQLException e) {
log.error("Failed to save order", e);
throw new OrderSaveException("Failed to save order", e);
}
catch (SQLException e) {
log.error("Failed to save order", e);
throw new OrderSaveException("Failed to save order", e);
}
Now picture the repository, service, and controller all doing this. One database failure prints three stack traces. Nobody can tell how many failures happened.
Different layers can still record different events. Your API layer can note that a checkout failed for this user. Your data layer deals with the actual exception. Nothing wrong with that. Just don’t print one stack trace three times.
6. Never Let Secrets Sneak Into Your Logs
Most leaks through logs start as debugging shortcuts, like this one:
logger.debug("Incoming booking request", { request: req.body });
logger.debug("Incoming booking request", { request: req.body });
In a hotel booking app, that body could have a card number in it. An auth token. Maybe a passport number. Now it’s all sitting in plain text. And way more people can read your logs than your database.
OWASP has a Logging Cheat Sheet with a list of what should be kept out of your logs. Passwords, session IDs, access tokens, and encryption keys are on it. So are card details and anything sensitive about a person.
People forget. I forget. So put the protection inside the logger, where nobody has to remember it. Strip sensitive fields in one shared place.
And use an allow-list, which names the fields you let through. A block-list will miss the field someone adds next month.
Need to track a session? Please don’t log the raw session ID. A hash of it is much safer, and OWASP suggests it too.
A keyed HMAC goes one step further. Someone could try to match a leaked log against session IDs from another system. Without your secret key, they can’t. You still want short retention and tight access, though.
Here’s one people often miss. A user ID, a city, two booking dates. Put them side by side, and you may have enough to spot one guest.
Log injection is the other OWASP concern. Never trust what users send you. Escape newline and delimiter characters. Then encode values for your log format, such as JSON.
To keep all of this honest, add a test. Push a fake card number and a fake token through a request. Spot either one in the output? The build fails.
7. Make Your Logs Answer Real Questions
Principle one made each line readable. This one is about the whole request.
Go back to the payment flow. A product manager asks a simple question.
Are premium users in Tokyo seeing slower checkouts?
Did it start with the new payment page?
With scattered log lines, you would add new logs, ship them, and wait a week.
The fix is a wide event. When a request finishes, you emit one structured event. It holds everything you know about that request. Some teams call this a canonical log line.
Define its fields in an approved schema, and control who can query it. This event holds user_id and city, so principle six applies in full.
{
"event": "checkout_completed",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"user_id": "usr_8812",
"plan": "premium",
"city": "Tokyo",
"new_payment_page": true,
"status": "success",
"duration_ms": 2840,
"db_queries": 14
}
{
"event": "checkout_completed",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"user_id": "usr_8812",
"plan": "premium",
"city": "Tokyo",
"new_payment_page": true,
"status": "success",
"duration_ms": 2840,
"db_queries": 14
}
Now the question becomes a query. Filter by plan and city, then compare duration_ms with the flag on and off.
Hold off on blaming the new page just yet. This shows you where to dig.
Maybe the new page got more mobile users, or more people paying by bank transfer. Rule those out before you call it.
The event must also fire for failed and partial requests. Record the status and the step where the request stopped.
A wide event summarizes one operation. It doesn’t replace detailed logs or traces. You still need those to explain failures and retries along the way.
Pick the event boundary to match the work. One event per request suits a web API. A long-running job or a streaming connection may need one event per batch or step.
Sample fast, successful events as in principle two. Tail-based sampling is a tracing technique, so wide log events need their own policy.
You don’t need this on day one. A small monolith with good structured logs may be enough for years. When you’re ready, start in your middleware and grow the event one field at a time.
My Logging Code Review Checklist
When I review a pull request, I read the logs just as closely as the code.
Here’s what I look for, every single time.
- Write for a Stranger. Every log line makes sense without the source code next to it. It names the entity, the outcome, and the reason.
- Log With a Purpose. Each new line has a reader and a purpose. Step-by-step detail lives at DEBUG, with its volume under control.
- Never Hide a Branch. Every
catch, fallback and retry branch is visible somewhere. That could be a log, a metric, or a trace. - Structure Every Field. Logs use structured fields. Request and trace context come from the logger itself, so no call site has to remember them.
- Keep Levels Honest. Levels follow our written team convention. Expected failures are not application errors. Bad input and a single wrong password are good examples.
- Log Each Failure Once. The same exception and stack trace appear once, at the layer that handles the failure.
- Keep Secrets Out. No raw request objects, tokens, or card data reach the logger. Redaction happens in one central place.
- Summarize Each Unit of Work. Where it fits, each unit of work emits one summary event, including when it fails or stops partway.
Start Before the Incident
Every principle here has one thing in common. You apply it while you design a feature and review its code, long before anything breaks.
Once an incident starts, you can only work with the logs you already shipped. The support desk showed me that years ago. It took me much longer to act on it.
Every log line is a message to a teammate you haven’t met yet.

