日志记录记录您的应用程序执行的操作;监控跟踪其健康状况和性能。一起来说,它们为您提供可观测性 — 理解和调试正在运行的生产系统的能力。console.log 对此不足以满足;您需要结构化日志、指标和告警。
结构化日志记录(不是 console.log)
js
pino ;
logger = ();
logger.({ : , : , : req. }, );
logger.({ err, requestId }, );
使用结构化 logger(pino/winston)输出具有一致字段的 JSON。与自由形式的 console.log 字符串不同,JSON 日志在日志聚合工具中是可搜索和可过滤的。在每条日志中包含上下文(用户 id、请求 id)。
Levels: error > warn > info > debug (configure threshold per environment)
Log: requests, errors with stack traces, key business events, slow operations
DON'T log: passwords, tokens, PII, full payloads with secrets (security/privacy)
// attach a unique id per request, include it in EVERY log for that request
app.use((req, res, next) => {
req.id = crypto.randomUUID();
res.setHeader("X-Request-Id", req.id);
next();
});
// now you can filter all logs for one request — vital in microservices
关联/请求 ID 让您即使跨多个服务也能重建单个请求的完整故事 — 对于调试分布式系统至关重要。
Ship logs to a central platform (ELK/Elasticsearch, Datadog, Grafana Loki, CloudWatch)
→ search/aggregate across all instances; don't grep files on individual servers.
Metrics: request rate, error rate, latency (p50/p95/p99), CPU/memory, event-loop lag
(often via Prometheus + Grafana, or an APM like Datadog/New Relic)
Health: /health & /ready endpoints for load balancers and orchestrators
Alerting: notify (PagerDuty/Slack) when error rate spikes or latency degrades
Tracing: distributed tracing (OpenTelemetry) to follow requests across services
Errors: error tracking (Sentry) for aggregated exceptions with stack traces & context
要监视的关键指标是**
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠