logging-best-practices

Các phương pháp ghi log tốt nhất tập trung vào các sự kiện rộng (dòng log chuẩn) để hỗ trợ gỡ lỗi và phân tích mạnh mẽ

npx skills add https://github.com/neondatabase/mcp-server-neon --skill logging-best-practices

Logging Best Practices Skill

Version: 1.0.0

Purpose

This skill provides guidelines for implementing effective logging in applications. It focuses on wide events (also called canonical log lines) - a pattern where you emit a single, context-rich event per request per service, enabling powerful debugging and analytics.

When to Apply

Apply these guidelines when:

  • Writing or reviewing logging code
  • Adding console.log, logger.info, or similar
  • Designing logging strategy for new services
  • Setting up logging infrastructure

Core Principles

1. Wide Events (CRITICAL)

Emit one context-rich event per request per service. Instead of scattering log lines throughout your handler, consolidate everything into a single structured event emitted at request completion.

const wideEvent: Record<string, unknown> = {
  method: 'POST',
  path: '/checkout',
  requestId: c.get('requestId'),
  timestamp: new Date().toISOString(),
};

try {
  const user = await getUser(c.get('userId'));
  wideEvent.user = { id: user.id, subscription: user.subscription };

  const cart = await getCart(user.id);
  wideEvent.cart = { total_cents: cart.total, item_count: cart.items.length };

  wideEvent.status_code = 200;
  wideEvent.outcome = 'success';
  return c.json({ success: true });
} catch (error) {
  wideEvent.status_code = 500;
  wideEvent.outcome = 'error';
  wideEvent.error = { message: error.message, type: error.name };
  throw error;
} finally {
  wideEvent.duration_ms = Date.now() - startTime;
  logger.info(wideEvent);
}

2. High Cardinality & Dimensionality (CRITICAL)

Include fields with high cardinality (user IDs, request IDs - millions of unique values) and high dimensionality (many fields per event). This enables querying by specific users and answering questions you haven't anticipated yet.

3. Business Context (CRITICAL)

Always include business context: user subscription tier, cart value, feature flags, account age. The goal is to know "a premium customer couldn't complete a $2,499 purchase" not just "checkout failed."

4. Environment Characteristics (CRITICAL)

Include environment and deployment info in every event: commit hash, service version, region, instance ID. This enables correlating issues with deployments and identifying region-specific problems.

5. Single Logger (HIGH)

Use one logger instance configured at startup and import it everywhere. This ensures consistent formatting and automatic environment context.

6. Middleware Pattern (HIGH)

Use middleware to handle wide event infrastructure (timing, status, environment, emission). Handlers should only add business context.

7. Structure & Consistency (HIGH)

  • Use JSON format consistently
  • Maintain consistent field names across services
  • Simplify to two log levels: info and error
  • Never log unstructured strings

Anti-Patterns to Avoid

  1. Scattered logs: Multiple console.log() calls per request
  2. Multiple loggers: Different logger instances in different files
  3. Missing environment context: No commit hash or deployment info
  4. Missing business context: Logging technical details without user/business data
  5. Unstructured strings: console.log('something happened') instead of structured data
  6. Inconsistent schemas: Different field names across services

Guidelines

Wide Events (rules/wide-events.md)

  • Emit one wide event per service hop
  • Include all relevant context
  • Connect events with request ID
  • Emit at request completion in finally block

Context (rules/context.md)

  • Support high cardinality fields (user_id, request_id)
  • Include high dimensionality (many fields)
  • Always include business context
  • Always include environment characteristics (commit_hash, version, region)

Structure (rules/structure.md)

  • Use a single logger throughout the codebase
  • Use middleware for consistent wide events
  • Use JSON format
  • Maintain consistent schema
  • Simplify to info and error levels
  • Never log unstructured strings

Common Pitfalls (rules/pitfalls.md)

  • Avoid multiple log lines per request
  • Design for unknown unknowns
  • Always propagate request IDs across services

References:

Thêm skills từ neondatabase

claimable-postgres
neondatabase
Cơ sở dữ liệu Postgres tức thì cho phát triển cục bộ, demo, tạo mẫu và môi trường thử nghiệm. Không yêu cầu tài khoản. Cơ sở dữ liệu hết hạn sau 72 giờ trừ khi được claim vào tài khoản Neon.
neon
neondatabase
Tổng quan về nền tảng Neon dành cho ứng dụng và tác nhân, bao gồm Postgres, Auth, Data API, và các dịch vụ mới: Object Storage, Compute Functions, và AI Gateway. Sử dụng bất cứ khi nào "Neon" được đề cập để có cái nhìn tổng quan về cách làm việc với Neon và cách bắt đầu. Nếu không, các khả năng riêng lẻ là các kích hoạt: "object storage" hoặc "S3-compatible storage", "serverless functions", "background jobs", hoặc "run code near my database", "AI gateway", "LLM proxy", "model routing", hoặc "call an LLM" →...
apidatabasedevelopment
plugin-manager
neondatabase
Quản lý cấu trúc và cấu hình plugin cho kho lưu trữ này trên cả Cursor và Claude Code. Sử dụng khi tạo, cập nhật hoặc xem xét các thư mục plugin…
skill-creator
neondatabase
Hướng dẫn tạo kỹ năng hiệu quả. Kỹ năng này nên được sử dụng khi người dùng muốn tạo một kỹ năng mới (hoặc cập nhật kỹ năng hiện có) để mở rộng khả năng của Claude…
using-neon
neondatabase
Hướng dẫn và các phương pháp tốt nhất khi làm việc với Neon Serverless Postgres. Bao gồm bắt đầu, phát triển cục bộ với Neon, chọn phương thức kết nối, Neon…
neon-js-react
neondatabase
Thiết lập đầy đủ Neon SDK với xác thực VÀ truy vấn cơ sở dữ liệu trong các ứng dụng React (Vite, CRA). Tạo client có kiểu, sinh kiểu cơ sở dữ liệu, và cấu hình…
postgres-best-practices
neondatabase
Các phương pháp và hướng dẫn tốt nhất khi làm việc với Postgres. Bao gồm thiết kế lược đồ, chiến lược lập chỉ mục, tối ưu hóa truy vấn, di chuyển dữ liệu và các lỗi thường gặp. Sử dụng…
neon-postgres-egress-optimizer
neondatabase
Hướng dẫn người dùng chẩn đoán và khắc phục các mẫu truy vấn phía ứng dụng gây ra việc truyền dữ liệu quá mức (egress) từ cơ sở dữ liệu Postgres của họ. Hầu hết các hóa đơn egress cao đến từ việc ứng dụng lấy nhiều dữ liệu hơn mức nó sử dụng.