跳到正文
cccskills
免费在 GitHub 公开

logging-best-practices

Implement structured logging with JSON formats, log levels (DEBUG, INFO, WARN, ERROR), contextual logging, PII handling, and centralized logging. Use for logging, observability, log levels, structured logs, or debugging.

中文简介正在准备中。当前显示原文说明。

集成工具AWSDatadog
查看安装方法

包含的文件(4)

  • SKILL.md6.1 KB
  • references/go.md1.1 KB
  • references/python.md1.2 KB
  • references/typescript.md5.8 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Logging Best Practices

Overview

Comprehensive guide to implementing structured, secure, and performant logging across applications. Covers log levels, structured logging formats, contextual information, PII protection, and centralized logging systems.

When to Use

  • Setting up application logging infrastructure
  • Implementing structured logging
  • Configuring log levels for different environments
  • Managing sensitive data in logs
  • Setting up centralized logging
  • Implementing distributed tracing
  • Debugging production issues
  • Compliance with logging regulations

Stack-Specific References

After reading the methodology below, read the reference matching your surface's Languages column:

LanguageReference
TypeScript / JavaScriptreferences/typescript.md
Pythonreferences/python.md
Goreferences/go.md

1. Log Levels

LevelWhen to UseProduction Default
DEBUGDetailed info for debugging — request payloads, intermediate valuesOFF
INFOGeneral operational events — user actions, transactions, startupON
WARNPotentially harmful — rate limits approaching, retry, deprecationsON
ERRORFailures the app can recover from — failed request, DB timeoutON
FATALCritical failures — the app must stopON (triggers alerts)

Environment rules:

  • Development: DEBUG and above
  • Staging: INFO and above
  • Production: INFO and above (DEBUG only via feature flag for specific modules)

2. Structured Logging (JSON)

All production logs MUST be structured (JSON format), not free-text. Structured logs enable:

  • Machine-parseable log aggregation
  • Field-based search and filtering
  • Dashboards and alerting

Every log entry must include:

  • timestamp — ISO 8601 format
  • level — log level string
  • message — human-readable description
  • service — service name
  • environment — deployment environment

Example output (any language):

{
  "timestamp": "2024-01-15T10:30:00.000Z",
  "level": "INFO",
  "message": "User created",
  "service": "user-service",
  "environment": "production",
  "userId": "abc-123",
  "requestId": "req-456"
}

3. Contextual Logging

Request Context

Attach request metadata to every log within a request lifecycle:

  • Request ID — unique identifier for correlating logs from one request
  • Correlation ID — propagated across service boundaries in distributed systems
  • User ID — authenticated user (if available)
  • HTTP method/path — what was requested

Correlation IDs

In distributed systems, propagate a correlation ID via headers (X-Correlation-Id) so that logs from multiple services can be traced together.


4. PII and Sensitive Data Handling

CRITICAL: PII must NEVER appear in plaintext in logs.

Sensitive Fields (always redact or mask)

  • Passwords, tokens, API keys
  • SSN, credit card numbers
  • Email addresses (depending on regulation)
  • Phone numbers (depending on regulation)

Strategies

StrategyWhen to Use
Redaction — replace with [REDACTED]Passwords, API keys, tokens
Masking — partial reveal (u***r@example.com)Email, phone, credit card
Hashing — one-way hashWhen you need to correlate without revealing
Omission — don't log the field at allWhen the field serves no diagnostic purpose

5. Performance Logging

Track operation timing for performance monitoring:

  • Start timer before operation
  • End timer after operation
  • Log duration with context
  • Alert on threshold if operation exceeds expected time

Key operations to time:

  • Database queries
  • External API calls
  • File I/O operations
  • Complex computations

6. Centralized Logging

For distributed systems, aggregate logs to a central system:

ToolType
ELK StackElasticsearch + Logstash + Kibana (self-hosted)
Grafana + LokiLightweight log aggregation (self-hosted)
DatadogCloud monitoring and logging
AWS CloudWatchAWS-native log management
SplunkEnterprise log management

7. Distributed Tracing

For microservice architectures, use OpenTelemetry (or similar) to trace requests across services:

  • Create spans for each operation
  • Propagate trace context via headers
  • Export to Jaeger, Zipkin, or Datadog

8. Log Sampling (High-Volume Services)

For high-volume services, sample INFO/DEBUG logs to reduce volume:

  • Random sampling — log N% of requests
  • Consistent sampling — hash user ID so same user always gets logged (or not)
  • Always log WARN and ERROR — never sample these

Best Practices

✅ DO

  • Use structured logging (JSON) in production
  • Include correlation/request IDs in all logs
  • Log at appropriate levels (don't overuse DEBUG)
  • Redact sensitive data (PII, passwords, tokens)
  • Include context (userId, requestId, etc.)
  • Log errors with full stack traces
  • Use centralized logging in distributed systems
  • Set up log rotation to manage disk space
  • Monitor log volume and costs
  • Use async logging for performance
  • Include timestamps in ISO 8601 format
  • Log business events (user actions, transactions)
  • Set up alerts for error patterns

❌ DON'T

  • Log passwords, tokens, or sensitive data
  • Use print/console.log in production
  • Log at DEBUG level in production by default
  • Log inside tight loops (use sampling)
  • Include PII without anonymization
  • Ignore log rotation (disk will fill up)
  • Use synchronous logging in hot paths
  • Log to multiple transports without need
  • Forget to include error stack traces
  • Log binary data or large objects
  • Use string concatenation (use structured fields)
  • Log every single request in high-volume APIs

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Audit and improve web accessibility following WCAG 2.1 guidelines. Use when asked to "improve accessibility", "a11y audit", "WCAG compliance", "screen reader support", "keyboard navigation", or "make accessible".

中文简介正在准备中。当前显示原文说明。

RepairYourTech/cfsa-antigravity62026年8月16日 更新

Structured methodology for adversarial thinking — generating attack scenarios, abuse cases, race conditions, and security edge cases against specs and implementations. Produces spec-level gap items, not code-level fixes.

中文简介正在准备中。当前显示原文说明。

RepairYourTech/cfsa-antigravity62026年8月16日 更新

Orchestrate multiple Antigravity skills through guided workflows for SaaS MVP delivery, security audits, AI agent builds, and browser QA.

中文简介正在准备中。当前显示原文说明。

RepairYourTech/cfsa-antigravity62026年8月16日 更新

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.

中文简介正在准备中。当前显示原文说明。

RepairYourTech/cfsa-antigravity62026年8月16日 更新

Manage API versioning and evolution with URL/header/query strategies, deprecation workflows, breaking change classification, sunset headers, and consumer-driven contract testing. Use when designing versioning strategy, deprecating endpoints, or evolving API contracts.

中文简介正在准备中。当前显示原文说明。

RepairYourTech/cfsa-antigravity62026年8月16日 更新

Analyzes codebase structure, data flow, module relationships, and key patterns to generate and maintain a living architecture document (ARCHITECTURE.md).

中文简介正在准备中。当前显示原文说明。

RepairYourTech/cfsa-antigravity62026年8月16日 更新

查看 RepairYourTech 的全部技能

报告此技能的问题