본문으로 건너뛰기
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(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

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 / 1,000자

이 양식은 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의 스킬 모두 보기

이 스킬의 문제 신고