Fixed Seven-Field JSON Logger: How a Full-Stack Project Logs Frontend and Backend Without Losing the Trail
How to Log Frontend and Backend: Levels, JSON Format, Daily Files, and Retention Policy
Here's the one-line rule for logging: the backend outputs one line of JSON per event, with seven fixed fields, writing all INFO and above to app.log, and ERROR and above also to a separate error.log, rotating daily and retaining 30 days; frontend errors are captured 100%, behavior is sampled at 10%, batched via sendBeacon; carry trace_id throughout, and redact before writing to disk. Below, each decision in this setup is broken down. 🎯
I recently maintain a small full-stack project with a React frontend and FastAPI backend, deployed on a single cloud host. Logs were initially scattered print and console.log statements. Once an order endpoint returned 500, the backend only left a line ZeroDivisionError, with neither user ID nor request ID, and the frontend timestamp didn't match the backend. Debugging was guesswork; a security scan later showed plaintext phone numbers in logs. The levels, fields, rotation, and redaction parameters in this article are the version actually running after that rework.
Table of Contents
- Five decisions before the first log line
- Log levels: five are enough, don't invent a sixth
- Format: one line of JSON per event, seven fixed fields
- Frontend: errors full, behavior sampled
- Backend: three strands—entry, exception, business
- Storage: file first, then platform
- Single vs. split files: daily primary, level fallback
- Rotation and retention: how big, how long, how archived
- Frequency: every time, sampled, or never
- Security and cost: redaction checklist and self-audit
1. Five Decisions Before the First Log Line (Five Decisions)
The reason "how should logs be recorded" gets confusing is that it's actually five independent decisions bundled together: what levels to record, what format to use, where to write, how to split files, and how long to keep them. If any one is undecided, the other four will be redone. 🔄
First, the central concept: a logging system is a set of conventions that writes runtime events into searchable records, covering five parts: levels, format, sink, splitting, and retention. It replaces scattered print and console.log in code: those are visible only in a local terminal, vanish when the process restarts, and cannot string together frontend and backend records by request; effectively useless when something goes wrong in production. Its operation is a one-way chain: application produces event → formatted into one line of JSON → routed by level to different files → rotated and cleaned by time or size → collected to a platform for querying and alerting, with trace_id throughout and redaction before writing to disk.
This chain is like package sorting: events are packages, levels are the priority on the label, format is the uniform packaging, trace_id is the same order number, and rotation and retention are the warehouse shelves and cleanup rules. Miss any link, packages can still come in but can't be found, don't line up, and pile up to overflow.
The table below is compiled from my own pitfalls; five symptoms map to five decisions:
| Symptom | Cause | Solution |
|---|---|---|
| Error online, not found in logs | Production only has print, or level set to WARNING swallowed the scene |
Set levels: §2, production starts at INFO |
| One request's logs spread across a dozen files | No unified trace_id, frontend and backend each log separately |
Set format: §3, seven fields must include trace_id |
| Logs dozens of GB per day, disk alarm | Every loop, every health check logs a line | Set frequency: §9, three tiers |
| Old logs already overwritten when a problem occurs | Single file without rotation, or retention set to 7 days | Set splitting and retention: §7, §8 |
| Phone numbers, Tokens in plaintext in logs | Directly printed request body, no redaction | Set security boundary: §10, whitelist plus masking |
My suggestion is to copy these five lines into the project's README before touching code—once the five decisions are made, the rest is just configuration.
2. Log Levels: Five Are Enough, Don't Invent a Sixth (Log Levels)
Among the five decisions, levels are the most contentious: some want DEBUG fully on, others want only ERROR. Look at the industry's common base—the syslog protocol defines 8 severity levels, from Emergency (0) to Debug (7) (RFC 5424); application layers usually drop the top three and converge to five. 🔍
| Level | When to use | Output in production | Example |
|---|---|---|---|
| DEBUG | Development-time detail, includes variable values | Default off | Cache miss, back to DB |
| INFO | Normal business milestones, can reconstruct main flow | On | Order created successfully, order_id=1024 |
| WARNING | Recoverable anomalies, note but don't alert | On | Third-party API timeout, retry succeeded |
| ERROR | Request failed, needs human intervention | On, also written separately | Order throws exception, returns 500 |
| FATAL | Process-level unrecoverable, service about to exit | On, triggers alert | Database connection pool exhausted and cannot rebuild |
The boundary is one sentence: should the on-call person be woken when this record appears. If yes, ERROR and above; if no but worth a look, WARNING; pure process information, INFO; only the developer cares, DEBUG. Coralogix's practice guide also draws the line by "degree of action required" (Coralogix). ⚠️
For production default, I lean toward INFO; DEBUG often triples to quintuples log volume, and what production really needs (input summaries, key branches, result codes) is covered by INFO. AWS's performance engineering guide similarly suggests only necessary levels in production, leaving detailed logs for on-demand temporary enabling (AWS Prescriptive Guidance).
Two frequently overlooked costs: string concatenation—log.debug("user:" + userId + " miss") executes concatenation even when the level is off; the correct form is placeholders log.debug("user:%s miss", userId), letting the framework format after checking the level, a rule in the Alibaba Java Development Manual's logging spec (p3c 日志规约). Second, logging only the message without the stack: log.error(str(e)) drops the call stack; the correct approach is to pass the exception object so the Formatter outputs an exception field.
3. Format: One Line of JSON Per Event, Seven Fixed Fields (Log Format)
Levels decide which events deserve writing; format decides what a record looks like. The split here is plaintext vs. JSON: plaintext is easier for humans to read, but production debugging relies on grep with regex; order changes break matches. Structured logging means each record is a fixed-field JSON object that machines can parse, index, and filter by field—one event per line, no newlines, no large nested objects (syntaqx).
I fixed seven fields, sufficient and not bloated:
| Field | Type | Meaning | Example |
|---|---|---|---|
timestamp |
string | ISO 8601 with timezone, UTC | 2026-12-01T08:30:15.123Z |
level |
string | One of five levels | ERROR |
service |
string | Service name, front and back same rule | order-api |
env |
string | Environment identifier | prod |
module |
string | Code module or file | order.service |
trace_id |
string | Unique ID for the whole request chain | 7f3a9c21e0b44d18 |
message |
string | A human-readable sentence | Order failed: inventory deduction exception |
These seven are not arbitrary. OpenTelemetry's log data model lists Timestamp, TraceId, SeverityText, Body as required or recommended (OpenTelemetry 中文文档), and community practice converges on a minimal set of timestamp, level, service, traceId, and message (掘金). I added env and module to the minimal set: when the same service is queried across environments, without env you guess; without module you resort to fuzzy matching message keywords. 💡
Business context doesn't go into message; it goes through a whitelist extra: user_id, path, method, status_code, duration_ms are the five allowed, everything else is discarded. A whitelist, not a blacklist, because blacklists always leak—today you think of passwords, tomorrow you forget ID card numbers.
Three conventions for the team spec, or fields are chaos in three months: field names are always snake_case; time is always stored UTC, converted to local timezone at the presentation layer (mixing timezones is the most time-consuming pitfall during incidents); message contains one human sentence, no JSON fragments, no concatenated variable values—variables live in extra. ⚠️
4. Frontend: Errors Full, Behavior Sampled (Frontend Logging)
After backend format is settled, it's frontend's turn. The biggest difference between frontend and backend logging is that logs get lost: a user clicks a page, generating a record; if you only console.log, that record exists only in the user's own browser console, forever invisible to you. So frontend "recording" must include the "reporting" step—frontend tracking is the frontend actively sending behavior and exception events back to the server; it's a kind of logging. 📤
Collection scope is divided into three categories with different strategies:
| Category | Content | Strategy |
|---|---|---|
| Errors | JS exceptions, Promise rejections, resource load failures, interface 5xx | 100% full |
| Performance | First-screen time, interface duration, white-screen detection | 10% sampling |
| Behavior | Clicks, route changes, key business operations | 10% sampling |
Errors must be full because errors are sparse; sampling is a blind lottery. Performance and behavior on a per-user-per-action scale would blow up bandwidth and storage if fully sent. Tencent Cloud's frontend monitoring practice also uses errors at 100%, performance at 10% sampling, batched every 10 records or 5 seconds (腾讯云开发者社区).
The reporting channel matters: ordinary fetch is cancelled by the browser on page unload, so the last batch is always lost; navigator.sendBeacon() is designed for this scenario—the browser guarantees the request goes out even after the page closes (MDN). So the strategy: while the page is alive, accumulate a batch, send via fetch when it reaches 10 records or 5 seconds; listen for the pagehide event and flush the remaining buffer with sendBeacon in one shot.
// Frontend log collection: errors full, behavior sampled, batch + page-close fallback reporting
const ENDPOINT = "/api/logs"; // Collection endpoint, unified backend receiving
const SAMPLE_RATE = 0.1; // Behavior and performance sampling rate 10%
const BUFFER = []; // Memory buffer, holds up to 10 records
let timer = null; // Timer handle, 5-second fallback
// Generate trace_id: reuse the value returned in the backend response header if present, otherwise generate locally
function getTraceId() {
return window.__TRACE_ID__ || crypto.randomUUID(); // Same ID shared between frontend and backend for the same request
}
// Write one log record: decide sampling by type, flush immediately when 10 are full
function logEvent(type, payload) {
if (type !== "error" && Math.random() > SAMPLE_RATE) return; // Non-error types 10% sampled
BUFFER.push({ // Assemble a structured record
timestamp: new Date().toISOString(), // UTC time, aligned with backend field
level: type === "error" ? "ERROR" : "INFO", // Errors map to ERROR, others INFO
service: "web", // Frontend unified service name
env: import.meta.env.MODE, // Vite-injected environment identifier
module: payload.module || "unknown", // Error module or page name
trace_id: getTraceId(), // Link ID, ties front and back together
message: payload.message, // One-sentence description
});
if (BUFFER.length >= 10) flush(); // Flush immediately when 10 are full
}
// Send buffer: normal fetch, unload stage goes to sendBeacon
function flush(useBeacon = false) {
if (!BUFFER.length) return; // Empty buffer returns directly
const body = JSON.stringify(BUFFER.splice(0)); // Take out and clear to avoid double-sending
if (useBeacon && navigator.sendBeacon) {
navigator.sendBeacon(ENDPOINT, new Blob([body], { type: "application/json" })); // Delivered even if page closes
} else {
fetch(ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json" }, body, keepalive: true });
}
}
// Global fallback: uncaught exceptions and Promise rejections both log ERROR
window.addEventListener("error", (e) => logEvent("error", { message: e.message, module: e.filename }));
window.addEventListener("unhandledrejection", (e) => logEvent("error", { message: String(e.reason) }));
window.addEventListener("pagehide", () => flush(true)); // Close/navigate away before sendBeacon
setInterval(() => flush(), 5000); // Fallback every 5 seconds
Two frontend-specific pitfalls. First, production code is minified; line numbers in error stacks don't match source code, so you must upload sourcemaps to the monitoring platform for restoration, and sourcemaps must never be publicly deployed—that's giving away your source. Second, never collect input field contents, passwords, tokens, full cookies, or ID numbers; the frontend is closest to the user, and one accidental collection is a data leak. The frontend baseline is 100% error delivery; behavior sampling is just a bonus. The collection boundary matters more than coverage. 🚫
5. Backend: Entry, Exception, Business Three Strands (Backend Logging)
The frontend carries trace_id in request headers; the backend's job is to receive it, thread it through, and write it to disk. Backend logging isn't sprinkling logger.info everywhere; it's three strands with distinct responsibilities: the entry strand records "who called what when", the exception strand records "why it failed and where the stack is", and the business strand records "what key state changed". All three carry the same trace_id so they can be stitched together on a platform. 🧵
Where logging code lives in the project has a rule. In How to Organize an Express Enterprise Project Structure, we discussed one-way dependency: logging is an infrastructure component that business layers can call, but it must not depend on business modules in reverse—otherwise a change in the logging module causes the whole project to fail compilation.
Where does trace_id come from? My approach is a middleware that generates it: if the request header has X-Trace-Id, reuse it (sent by frontend or upstream); otherwise generate a 32-character hex string, store it in contextvars, and also put it in the response header back to the frontend. This way subsequent frontend reports attach to the same chain. Microsoft's Azure Spring Apps documentation logs mdc.traceId as a separate column in the log table (Microsoft Learn), same idea.
The Python script below uses only the standard library, copy-paste and it runs. It includes five parts: JsonFormatter outputs seven-field JSON, TraceIdFilter injects the link ID, RedactFilter redacts, two Handlers route by level, and a demo function walks through both info and exception paths. 🛠️
"""Runnable minimal logging system: JSON format + trace_id + redaction + level routing."""
import json # Serialize each log to one line of JSON
import logging # Standard library logging framework
import logging.handlers # Provides handlers that rotate by time or size
import re # Regex for phone and email masking
import uuid # Generate trace_id
from contextvars import ContextVar # Request-level context, stores trace_id
from datetime import datetime, timezone # UTC timestamp
trace_id_var = ContextVar("trace_id", default="-") # Independent per request, default placeholder "-"
ALLOWED_EXTRA = {"user_id", "path", "method", "status_code", "duration_ms"} # extra whitelist
class JsonFormatter(logging.Formatter):
"""Format LogRecord into one line of JSON with seven fixed fields."""
def format(self, record):
"""Assemble fields and return a JSON string.
Args:
record: logging.LogRecord, one log record
Returns:
str: single-line JSON, fixed field order
"""
payload = {
"timestamp": datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
"level": record.levelname, # Five-level name
"service": "order-api", # Service name, change when deploying
"env": "prod", # Environment identifier
"module": record.name, # Logger name, usually module path
"trace_id": trace_id_var.get(), # Get link ID from context
"message": record.getMessage(), # Only human-readable sentence
}
for key in ALLOWED_EXTRA: # Only carry whitelisted business fields
if hasattr(record, key):
payload[key] = getattr(record, key)
if record.exc_info: # Append full stack trace on exception
payload["exception"] = self.formatException(record.exc_info)
return json.dumps(payload, ensure_ascii=False) # Chinese not escaped
class RedactFilter(logging.Filter):
"""Redact before writing to disk: mask password-style fields, phone numbers, and emails."""
def filter(self, record):
"""Modify record in place, return True to continue output.
Args:
record: logging.LogRecord, one log record
Returns:
bool: always True, passes after redaction
"""
message = record.getMessage()
message = re.sub(r"(password|token|secret)=\S+", r"\1=***", message, flags=re.I) # Mask sensitive keys entirely
message = re.sub(r"1[3-9]\d{9}", lambda m: m.group()[:3] + "****" + m.group()[-4:], message) # 138****5678
message = re.sub(r"([\w.+-]+)@([\w-]+\.\w+)", r"***@\2", message) # Hide email username
record.msg = message # Write back redacted message
record.args = () # Clear args to avoid re-formatting
return True
def build_logger():
"""Assemble two Handlers for app.log and error.log, return root logger."""
logger = logging.getLogger("order.service")
logger.setLevel(logging.INFO) # Production default INFO
formatter = JsonFormatter()
app_handler = logging.handlers.TimedRotatingFileHandler(
"logs/app.log", when="midnight", backupCount=30, encoding="utf-8")
app_handler.setLevel(logging.INFO) # INFO and above all into app.log
error_handler = logging.handlers.RotatingFileHandler(
"logs/error.log", maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8")
error_handler.setLevel(logging.ERROR) # Only ERROR and above into error.log
for handler in (app_handler, error_handler):
handler.setFormatter(formatter)
handler.addFilter(RedactFilter()) # Redact at both outputs
logger.addHandler(handler)
return logger
def handle_order(order_id: str, amount: int):
"""Demonstrate business INFO and exception paths."""
logger.info("Order start order_id=%s", order_id, extra={"path": "/orders", "method": "POST"})
try:
unit_price = amount / 0 # Deliberately cause ZeroDivisionError
logger.info("Order success order_id=%s price=%s", order_id, unit_price)
except ZeroDivisionError:
logger.exception("Order failed order_id=%s", order_id) # Automatically includes full stack trace
raise
if __name__ == "__main__":
import os
os.makedirs("logs", exist_ok=True) # Ensure log directory exists
logger = build_logger()
trace_id_var.set(uuid.uuid4().hex) # Simulate middleware injecting trace_id
try:
handle_order("1024", 100)
except ZeroDivisionError:
pass
print(open("logs/app.log", encoding="utf-8").read()) # Echo app.log content
After running, app.log has two records: one INFO "Order start", one ERROR "Order failed" with exception field; error.log has only the ERROR. The trace_id matches in both—that's the minimal evidence tying together one request.
If message contains a phone number, e.g., 下单开始 phone=13812345678, it gets changed to 138****5678 by RedactFilter before hitting disk. Redaction lives at the Handler layer rather than in business code because business code always has branches that get missed; a single exit point is the only way to hold the line.
6. Storage: File First, Then Platform (Log Storage)
With format and strands done, the next question is where things go. Three common destinations, very different scale:
| Sink | Use case | Pros | Cost |
|---|---|---|---|
| Local file | Single-machine deployment, daily requests under millions | Zero dependencies, direct grep, lowest cost |
No aggregation across instances, full disk can drag down service |
| stdout | Containerized deployment (Docker / K8s) | Decoupled from container lifecycle, platform collects uniformly | Not visible locally, needs an agent |
| Log platform | Multiple instances, needs search and alerting | Full-text search, dashboards, alerts | Has cost, config changes |
For containers, I lean toward writing to stdout—this is the original Twelve-Factor App recommendation: the app treats logs as an event stream, writing one line per event to standard output, and the runtime environment is responsible for collection and routing (CNCF Blog). The app shouldn't manage file rotation itself—when the container is destroyed, files written inside it vanish with it. 📦
Lay out the whole chain. This diagram groups by "data flow", from the user's browser on the far left to the alert dashboard on the far right:
flowchart LR
A[Frontend events<br/>Error/Behavior/Performance] -->|sendBeacon batch report| B[Collection gateway<br/>/api/logs]
B --> C[Backend middleware<br/>inject trace_id]
C --> D[JsonFormatter<br/>seven-field serialization]
D --> E{Route by level}
E -->|INFO and above<br/>including errors| F[app.log]
E -->|ERROR and above| G[error.log]
F --> H[Rotate daily<br/>compress archive]
G --> H
H -->|Collection Agent| I[Log platform<br/>search and alerting]
There's an easily overlooked detail in the diagram: error.log is not a replacement for app.log, but an additional copy. ERROR events land in both files—app.log keeps the full timeline, error.log keeps only errors for quick browsing. That's the origin of "level fallback" in the next chapter.
For single-machine VM deployment, the opposite: writing to files directly is easier—no agent to install, tail -f works when something happens. My small project is a single machine, so files it is; when instance count exceeds two, move to a platform.
One sink is explicitly off the table: don't write business logs into a database. Logs are append-heavy, voluminous, almost never updated; stuffing them into a relational DB competes for connections and IO with business queries. One slow query can clog log writes and throttle the business in return. Audit logs can go to a DB (need transactions and queries); runtime logs cannot. ❌
7. Single File vs. Split Files: Daily Primary, Level Fallback (File Splitting)
With the sink set to files, next is file layout: split or single, by function or another dimension. My conclusion: daily is the main line, level split is the only necessary secondary line, and by-function split generally isn't worth it. First look at the costs of three dimensions: 📂
| Split dimension | Pros | Cost | Use |
|---|---|---|---|
| Daily | Aligns with debugging habit (first ask "what day was the problem"), rotation rule simple | Single day can still be large | All scenarios, default choice |
| By level | Errors concentrated, fastest to browse error.log |
Cross-level correlation goes back to app.log, same event may be written twice |
As fallback, only additionally split ERROR |
| By module/function | Single-module problems focused | File count explodes, cross-module requests can't be stitched, trace_id queries span multiple files |
Few modules and highly unbalanced log volume |
The biggest problem with splitting by function isn't inconvenience—it's breaking the chain: an order goes through order, inventory, and payment modules; split by module, and the same request's logs are scattered across three files, making it harder to trace—exactly the opposite of trace_id's goal. So unless one module's log volume is an order of magnitude higher than the others, don't split by function.
For a single-machine project under four machines, I'd lay it out: logs/app.log full, logs/error.log only errors; both rotate daily, distinguished by date in the filename, no further subdirectories. Whether to split, walk through this decision tree:
flowchart TD
A[Start: need to split?] --> B{Log volume exceeds<br/>1 GB per day}
B -->|No| C[Single file daily rotation<br/>app.log]
B -->|Yes| D{Need fast error location}
D -->|Yes| E[Daily + level<br/>app.log / error.log]
D -->|No| F{Single module share<br/>exceeds 80%}
F -->|Yes| G[Daily + module<br/>only split hotspot]
F -->|No| E
C --> H[Unify with trace_id]
E --> H
G --> H
The diagram forks on "volume → location need → module skew", not by function. Going through it, most projects stop at the second layer; splitting by module is the escape hatch for extreme imbalance.
For multi-instance, an implicit convention: filenames carry instance identifiers, e.g., app-10.0.1.7.log, otherwise after collection you can't trace which machine wrote it. This can also go into the JSON extra field, which is more reliable than the filename.
8. Rotation and Retention: How Big, How Long, How Archived (Rotation & Retention)
File splitting rules are set; rotation and retention are two halves of the same thing: too fragmented, too many files to manage; too large, a single grep scans several GB. Keep too short, logs are gone at incident review; keep too long, disk fills first. ⏳
Rotation has two trigger modes, corresponding to two Python standard-library Handlers:
| Handler | Trigger | Example parameters | Suits |
|---|---|---|---|
TimedRotatingFileHandler |
Time (midnight) | when="midnight", backupCount=30 |
Main logs, daily rotation |
RotatingFileHandler |
File size | maxBytes=10*1024*1024, backupCount=5 |
Error logs, control total size |
Parameter meanings are clear in Python docs: backupCount is the number of old files kept; beyond that, oldest are deleted (Python 3.12 logging.handlers). In the code, app.log rotates daily keeping 30, error.log rotates at 10 MB keeping 5, for a total cap around 50 MB—enough for a small single-machine project.
Retention tiers by level is common in the community: debug 3–7 days, info/warn 14–30 days, error 30–90 days (neverblink.ai); login and permission-change logs for security audits should retain 12–24 months (middleware.io). Strict industries have hard minimums—the CSRC's "Securities and Futures Operating Institution Internal Application System Logging Specification" requires logs generated as daily files, with high-security systems retaining no less than 36 months and mid/low no less than 12 (JR/T 0233—2021). If you work in that space, 30 days is only the baseline for runtime logs; audit logs need separate calculation.
My archiving preference is "hot 7 days + cold 30 days": last 7 days plaintext, direct grep; logs older than 7 days compressed to .gz and the originals deleted, decompress when needed. Text log compression is usually 80–90%, so a 1 GB log compresses to about 100–200 MB (StackPractices), relieving disk pressure immediately. 💾
Run the numbers to see if magnitudes line up. Assume peak 100 QPS, 2 logs per request, 500 bytes each, a full day: $100 \times 2 \times 500 \times 86400 \approx 8.64$ GB. That's the sustained-peak upper bound; real-world at 300k requests/day is only about 300 MB/day, compressed about 30–60 MB/day, under 2 GB for 30 days. When you see a "dozens of GB a day" alert, reverse-calculate whether QPS was overestimated or each log is too verbose. 🔢
9. Frequency: Every Time, Sampled, or Never (Frequency & Sampling)
Rotation and retention handle "how to manage what's already written"; frequency handles "what should be written at all". The most common failure isn't under-logging, but over-logging drowning useful signals: a line every loop, a line every heartbeat, and when something actually breaks you flip three pages in error.log to find the target. 📉
I divide logging frequency into three tiers:
| Tier | Events | Practice |
|---|---|---|
| Every time | Request entry and exit, state changes, payments and logins, exceptions | 100% full, no sampling |
| Sampled | Frontend behavior and performance, debug details on success paths, high-frequency polling | Sample by ratio, or hash modulo on trace_id |
| Never | Loop bodies, successful health checks, heartbeats, individual cache hits | Don't write, or lower to DEBUG with production off |
Health checks and loop logs are two typical traps. A load balancer probes every 5 seconds, 17,280 success records a day, all noise; the right move is to log WARNING only on failure, nothing on success. Loop-body logging is worse—a batch task processing 10,000 records instantly emits 10,000 lines; the correct place is start and end outside the loop, and only failures inside the loop.
Sampling has one consistency requirement: the same request is either fully sampled or not at all. If you flip a coin per log line, a failed request might leave only the entry log and drop the exception log, making debugging harder. The approach is hash modulo on trace_id, putting the same ID in the same bucket (ng-blog). I keep errors and state changes at 100% and sample only high-frequency success paths—what gets dropped should be duplicate information, not unique evidence. 💡
10. Security and Cost: Redaction Checklist and Self-Audit (Security & Cost)
With frequency settled, the last gate is security. The irony of logging: you record to debug, and the record itself becomes a leak channel. OWASP's logging cheat sheet lists a clear set of data that should never land in logs: session identifiers and access tokens, passwords, database connection strings, encryption keys, payment card numbers, personal sensitive information, and anything that could directly take over an account (OWASP Logging Cheat Sheet). 🔐
Redaction methods are chosen by data type, not always masking:
| Data type | Recommended treatment | Reason |
|---|---|---|
| Passwords, tokens, keys | Don't record, or replace entirely with *** |
No debugging value, leak is an incident |
| Phone numbers, emails | Mask, e.g., 138****5678 |
Preserve verifiability, remove identifiability |
| User IDs, order numbers | Plaintext or hash | Needed for debugging, internal identifiers are low risk |
| ID card numbers, bank card numbers | Don't record, or tokenize | High sensitivity, masking isn't enough |
Masking, hashing, and tokenization are the three methods given by OWASP ASVS 7.1.1; the choice is based on "does this value still need to be compared" (HoundDog.ai). To verify whether it's the same phone number, the last four digits of the mask suffice; to prevent cross-table correlation, hash with salt.
There's another vulnerability both frontend and backend often miss: log injection. A user input with a newline splits one log line into two, letting an attacker forge a fake record that looks like system output; if logs are JSON-stored, a newline breaks parsing. The fix is to escape \r and \n in the Formatter, or simply JSON-serialize the message—this is a hidden benefit of structured format: plaintext logs have no such protection. 🚨
Before delivery, go through your project with this checklist:
| Check item | Pass standard |
|---|---|
| Field completeness | Every log has the seven fixed fields, trace_id non-empty |
| Level correctness | No DEBUG in production; exceptions use exception rather than only the message |
| Routing and rotation | app.log daily, error.log by size, backupCount set |
| Retention period | Runtime logs ≥30 days, audit-class logs per compliance set separately |
| Redaction coverage | Passwords/tokens/phone/email/ID verified one by one on disk |
| Frontend boundary | No collection of input content, full cookies, or public sourcemap URLs |
| Injection protection | Newlines escaped, message has no raw user-input concatenation |
Writing this, the configuration has been running in my small project for months: on error, pull the whole chain by trace_id, then check error.log for the stack; average time-to-locate dropped from half an hour to a few minutes. Logs aren't the more the better—it's that the needed one happens to exist and can be connected. 🎯
References (References)
- OpenTelemetry log data model: https://opentelemetry.io/zh/docs/concepts/signals/logs/
- RFC 5424 The Syslog Protocol: https://www.rfc-editor.org/info/rfc5424
- Coralogix Application Logging Best Practices: https://coralogix.com/guides/application-performance-monitoring/application-logging-best-practices/
- AWS Prescriptive Guidance - Logging: https://docs.aws.amazon.com/prescriptive-guidance/latest/performance-engineering-aws/logging.html
- Alibaba Java Development Manual logging spec: https://alibaba.github.io/p3c/%E5%BC%82%E5%B8%B8%E6%97%A5%E5%BF%97/%E6%97%A5%E5%BF%97%E8%A7%84%E7%BA%A6.html
- Logs aren't the more the better: a landable logging design: https://juejin.cn/post/7626969207809867816
- syntaqx Logs·Observability: https://www.syntaqx.com/docs/observability/logs
- MDN Navigator.sendBeacon: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
- Tencent Cloud Developer Community - Frontend monitoring collection metrics: https://cloud.tencent.com.cn/developer/ask/2213473
- Microsoft Learn - Azure Spring Apps structured logs: https://learn.microsoft.com/zh-cn/azure/spring-apps/basic-standard/structured-app-log
- Python 3.12 logging.handlers: https://docs.python.org/3/library/logging.handlers.html
- CNCF Blog - Twelve-factor app anno 2022: https://www.cncf.io/blog/2022/04/28/twelve-factor-app-anno-2022/
- neverblink.ai - Log Management Best Practices: https://neverblink.ai/kb/log-management-best-practices
- middleware.io - Application logs guide: https://middleware.io/blog/application-logs/
- JR/T 0233—2021 Securities and Futures Operating Institution Internal Application System Logging Specification: http://www.csrc.gov.cn/csrc/c101950/c1560182/1560182/files/%E9%99%84%E4%BB%B62%EF%BC%9A%E8%AF%81%E5%88%B8%E6%9C%9F%E8%B4%A7%E4%B8%9A%E7%BB%8F%E8%90%A5%E6%9C%BA%E6%9E%84%E5%86%85%E9%83%A8%E5%BA%94%E7%94%A8%E7%B3%BB%E7%BB%9F%E6%97%A5%E5%BF%97%E8%A7%84%E8%8C%83.pdf
- StackPractices - Rotate Log Files: https://stackpractices.com/recipes/rotate-log-files/
- ng-blog - Frontend Observability: https://www.ng-blog.de/tutorials/frontend-observability-logging-tracing-web-vitals
- OWASP Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet
- HoundDog.ai - OWASP ASVS 7.1.1: https://docs.hounddog.ai/scanner/owasp-asvs-7-1-1
If you're running a small single-machine project, copy the default configuration directly; for multi-instance or strictly regulated scenarios, recompute levels and retention per §8's compliance minimums, don't blindly copy the 30 days.
This column "Full-Stack Development" focuses on frontend-backend engineering details: project structure, logging and monitoring, API boundaries, deployment and tuning, each with runnable code, updated weekly. To read in order, subscribe on the column page.
Top 2 of 3 from juejin.cn, machine-translated. The original thread is authoritative.
Logs are for AI to read, not for humans.
That's only half true. AI reads the entire time window, while a human troubleshooting only looks at the last few lines of anomalies. So the approach that actually passes on both sides is fixed fields plus single-line JSON: a human can locate it at a glance, and AI can be fed the whole chunk without reordering. Logs optimized purely for AI will make the human miserable the night a production incident happens.
Sampling by trace chain is what keeps the trail from breaking.