logging-best-practices

Logging best practices focused on wide events (canonical log lines) for powerful debugging and analytics

25 stars

Best use case

logging-best-practices is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Logging best practices focused on wide events (canonical log lines) for powerful debugging and analytics

Teams using logging-best-practices should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/logging-best-practices/SKILL.md --create-dirs "https://raw.githubusercontent.com/ComeOnOliver/skillshub/main/skills/Harmeet10000/skills/logging-best-practices/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/logging-best-practices/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How logging-best-practices Compares

Feature / Agentlogging-best-practicesStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Logging best practices focused on wide events (canonical log lines) for powerful debugging and analytics

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# 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.

```typescript
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:
- [Logging Sucks](https://loggingsucks.com)
- [Observability Wide Events 101](https://boristane.com/blog/observability-wide-events-101/)
- [Stripe - Canonical Log Lines](https://stripe.com/blog/canonical-log-lines)

Related Skills

visualization-best-practices

25
from ComeOnOliver/skillshub

Visualization Best Practices - Auto-activating skill for Data Analytics. Triggers on: visualization best practices, visualization best practices Part of the Data Analytics skill category.

logging-api-requests

25
from ComeOnOliver/skillshub

Monitor and log API requests with correlation IDs, performance metrics, and security audit trails. Use when auditing API requests and responses. Trigger with phrases like "log API requests", "add API logging", or "track API calls".

scanning-input-validation-practices

25
from ComeOnOliver/skillshub

This skill enables Claude to automatically scan source code for potential input validation vulnerabilities. It identifies areas where user-supplied data is not properly sanitized or validated before being used in operations, which could lead to security exploits like SQL injection, cross-site scripting (XSS), or command injection. Use this skill when the user asks to "scan for input validation issues", "check input sanitization", "find potential XSS vulnerabilities", or similar requests related to securing user input. It is particularly useful during code reviews, security audits, and when hardening applications against common web vulnerabilities. The skill leverages the input-validation-scanner plugin to perform the analysis.

implementing-database-audit-logging

25
from ComeOnOliver/skillshub

Process use when you need to track database changes for compliance and security monitoring. This skill implements audit logging using triggers, application-level logging, CDC, or native logs. Trigger with phrases like "implement database audit logging", "add audit trails", "track database changes", or "monitor database activity for compliance".

cloud-logging-sink-setup

25
from ComeOnOliver/skillshub

Cloud Logging Sink Setup - Auto-activating skill for GCP Skills. Triggers on: cloud logging sink setup, cloud logging sink setup Part of the GCP Skills skill category.

dotnet-best-practices

25
from ComeOnOliver/skillshub

Ensure .NET/C# code meets best practices for the solution/project.

SARIF Parsing Best Practices

25
from ComeOnOliver/skillshub

You are a SARIF parsing expert. Your role is to help users effectively read, analyze, and process SARIF files from static analysis tools.

oracle — best use

25
from ComeOnOliver/skillshub

Oracle bundles your prompt + selected files into one “one-shot” request so another model can answer with real repo context (API or browser automation). Treat output as advisory: verify against code + tests.

go-logging

25
from ComeOnOliver/skillshub

Use when choosing a logging approach, configuring slog, writing structured log statements, or deciding log levels in Go. Also use when setting up production logging, adding request-scoped context to logs, or migrating from log to slog, even if the user doesn't explicitly mention logging. Does not cover error handling strategy (see go-error-handling).

vue-pinia-best-practices

25
from ComeOnOliver/skillshub

Pinia stores, state management patterns, store setup, and reactivity with stores.

vue-options-api-best-practices

25
from ComeOnOliver/skillshub

Vue 3 Options API style (data(), methods, this context). Each reference shows Options API solution only.

next-best-practices

25
from ComeOnOliver/skillshub

Next.js best practices - file conventions, RSC boundaries, data patterns, async APIs, metadata, error handling, route handlers, image/font optimization, bundling