A practical logging schema for small SaaS teams focuses on high-signal, low-noise data that allows a developer to reconstruct a user's journey and identify the root cause of a failure without searching through millions of irrelevant lines. The goal is to move from "something is broken" to "this specific user encountered this specific error at this specific step" in under two minutes. To achieve this, you need a structured logging format (JSON) and a consistent set of keys across every service in your stack.
What You'll Need
- A structured logger library for your primary language (e.g., Winston for Node.js, Zap for Go, or Loguru for Python).
- A centralized log aggregator or storage solution (e.g., BetterStack, Datadog, ELK stack, or simple cloud-native logs like AWS CloudWatch).
- A standardized JSON format for all log outputs to ensure searchability.
Step-by-Step
- Establish a Global Correlation ID (Request ID). The most critical signal is a unique identifier generated at the edge (load balancer or API gateway) for every single incoming request. This ID must be passed in the headers to every downstream microservice or background worker involved in that request. When a user reports an error, you search for that one ID and see the entire lifecycle of the request across your whole system. Without this, you are guessing which logs in Service A correlate to logs in Service B.
- Implement the User and Organization Context. Every log entry should include the
user_idandorg_id(ortenant_id). In a multi-tenant SaaS, bugs are often isolated to a specific account due to data corruption or a specific configuration. Including these IDs allows you to filter logs for a single customer to see if their experience is anomalous or if a systemic issue is affecting everyone. If the request is unauthenticated, use asession_idorip_addressas a fallback. - Standardize Log Levels for Alerting. Avoid using
INFOfor everything. Use a strict hierarchy:DEBUGfor verbose developer data (disabled in production),INFOfor major state changes (e.g., "User signed up"),WARNfor handled exceptions that don't break the user experience (e.g., "API retry attempted"), andERRORfor events that require immediate attention or result in a failed request. Map your alerting system to trigger only onERRORlevels to avoid alert fatigue. - Capture the Precise Event Action. Instead of writing free-text messages like "The user clicked the button and it failed," use a structured
event_namekey. Use acategory.actionformat, such asbilling.subscription_updatedorauth.password_reset_requested. This transforms your logs into a searchable database of business events, allowing you to count how many times a specific action failed over the last hour without parsing strings. - Log the Request Metadata. Store the
method(GET, POST, etc.), theendpoint_path, and theresponse_time_ms. Tracking the latency of individual requests within your logs helps you identify "silent killers"—requests that don't fail but take 10 seconds to complete, causing the user to refresh the page and double-submit data. This provides a baseline for performance tuning without needing a full APM (Application Performance Monitoring) suite. - Include Detailed Error Context (The "Why"). When an
ERRORoccurs, do not just log the message. Log theerror_code, thestack_trace, and theinput_params(excluding passwords or PII). Knowing that a "Database Error" occurred is useless; knowing that it was a "Unique Constraint Violation on email_address" when the input was "test@example.com" allows you to fix the bug instantly without trying to reproduce it locally. - Track the Environment and Version. Add
env(production, staging, development) andapp_version(the git commit hash or semantic version). In a small team, you might deploy multiple times a day. If errors spike, the first question is always "Did this start after the last deploy?" Having the version tag in every log line allows you to correlate a spike inERRORlogs with a specific deployment timestamp.
Common Mistakes
One of the most frequent mistakes is logging PII (Personally Identifiable Information). Logging a user's plain-text password, credit card number, or full home address is a security violation and can lead to compliance failures. Always implement a scrubbing layer or a blacklist of keys (e.g., password, token, secret) that are automatically masked before the log is written to disk.
Another common pitfall is "Log Bloat," where developers leave DEBUG logs active in production. This doesn't just cost money in storage; it slows down the system and makes searching for actual errors like finding a needle in a haystack. Ensure your logging configuration is environment-aware, defaulting to INFO or WARN in production.
Finally, avoid using unstructured text strings for critical data. If you log "User 123 failed to login" instead of { "event": "login_fail", "user_id": 123 }, you cannot easily graph the failure rate or create a dashboard. You are forced to use expensive and slow regular expressions to extract the data you need.
Tips
To make your logs even more powerful, implement "Breadcrumbs." Breadcrumbs are a series of INFO level logs that track the path a user took leading up to an error. For example: user_entered_checkout → selected_shipping_method → clicked_pay_button → ERROR: payment_gateway_timeout. This sequence tells a story that a single error log cannot.
Consider implementing a "Sampling Rate" for your INFO logs if your traffic grows. Instead of logging every single successful request, log only 10% of them. You still get a statistical representation of system health and performance, but you drastically reduce your storage costs and log ingestion fees.
Integrate your logs with your error tracking tool. If you use a tool like Sentry or Honeybadger, include the correlation_id in the error report. This allows you to jump from a crash report directly into your log aggregator to see the 50 lines of context that happened immediately before the crash.
Troubleshooting
If you find that your logs are missing or incomplete, first check the log_level configuration in your environment variables. It is common for a production environment to be accidentally set to ERROR, which hides all INFO and WARN signals. Change the level to INFO and restart the service to verify.
If you are seeing "Log Gaps" (missing time periods), check your log aggregator's ingestion limits. Many free or low-tier plans have a daily cap on gigabytes. Once reached, logs are either dropped or delayed. If this happens, increase your log sampling rate or move more verbose logs to DEBUG level.
If you cannot find a specific request despite having the correlation_id, verify that the ID is being passed correctly through your middleware. Log the ID at the very first entry point of your application. If the ID is missing in downstream services, check your HTTP header propagation logic to ensure the X-Request-ID is being forwarded to every internal API call.
Frequently Asked Questions
Should I log every single API request?
For small teams, yes, but keep the logs lean. Log the request and response metadata (status code, latency) at the INFO level. As you scale, move to sampling to save on costs.
What is the difference between a log and a metric?
A log is a discrete event (e.g., "User X changed their password"), while a metric is an aggregation over time (e.g., "Average CPU usage is 40%" or "Total requests per second"). Logs are for debugging; metrics are for alerting and trending.
How long should I keep my logs?
For most small SaaS teams, a 14 to 30-day retention period is sufficient for debugging production issues. For compliance (like SOC2), you may need to archive logs to cheaper "cold storage" (like AWS S3) for a year or more.
Is JSON logging slower than plain text?
The performance overhead of generating JSON is negligible compared to the network latency of sending that log to a server. The massive gain in searchability and analysis far outweighs the tiny CPU cost.
Do I need a separate logging library for each microservice?
You should use a consistent library or a shared internal wrapper. The goal is for a log from the "Billing Service" to look exactly like a log from the "Auth Service" so you can query them together.