Logging Fundamentals
Establish proper logging practices including log levels, structured logging, context propagation, and comprehensive logging strategies for applications, services, and infrastructure.
When to use me
Use this skill when:
- Setting up logging for new applications or services
- Reviewing existing logging implementations
- Establishing logging standards for teams or projects
- Debugging issues with incomplete or poor logging
- Implementing structured logging for better observability
- Configuring log levels and verbosity for different environments
- Ensuring logs contain sufficient context for troubleshooting
What I do
1. Log Level Management
- Define appropriate log levels (DEBUG, INFO, WARN, ERROR, FATAL)
- Configure level filtering per environment (development, staging, production)
- Implement dynamic level adjustment without application restarts
- Establish level usage guidelines for different types of information
- Create level-based alerting thresholds for operational monitoring
2. Structured Logging Implementation
- Design log schema with consistent field naming and types
- Implement structured formats (JSON, key-value pairs, structured text)
- Include mandatory context fields (timestamp, service, trace_id, user_id, etc.)
- Handle nested structures and arrays appropriately in logs
- Ensure PII (Personally Identifiable Information) compliance in log content
3. Context Propagation
- Implement correlation IDs for request tracing across services
- Propagate context through async operations (queues, background jobs)
- Maintain user/session context throughout request lifecycle
- Include business context (order_id, transaction_id, etc.) in logs
- Handle context in distributed systems with proper header propagation
4. Log Content Best Practices
- Include sufficient context for debugging without external systems
- Balance detail with noise - log enough but not too much
- Use consistent message formats across the codebase
- Log before and after significant operations
- Include error details (stack traces, error codes, recovery suggestions)
- Avoid logging secrets, passwords, or sensitive data
5. Environment-Specific Configuration
- Development logging - Verbose, human-readable, local file output
- Staging logging - Balanced detail, structured format, aggregation
- Production logging - Minimal noise, structured only, remote aggregation
- Debug mode logging - Temporary increased verbosity for troubleshooting
Logging Principles
The 5 Ws of Logging
- WHO - Which user/service/process generated the log?
- WHAT - What action/event is being logged?
- WHEN - Precise timestamp with timezone information
- WHERE - Which component/function/file generated the log?
- WHY - What is the significance/severity of the logged event?
Structured Logging Fields
{
"timestamp": "2026-02-26T18:00:00Z",
"level": "ERROR",
"service": "payment-service",
"component": "process_payment",
"trace_id": "abc123-def456",
"span_id": "def456",
"user_id": "user-789",
"session_id": "session-xyz",
"request_id": "req-123456",
"message": "Payment processing failed",
"error_code": "PAYMENT_GATEWAY_TIMEOUT",
"error_details": "Gateway response timeout after 5000ms",
"stack_trace": "...",
"context": {
"order_id": "ord-987654",
"amount": 99.99,
"currency": "USD"
},
"duration_ms": 5123,
"environment": "production",
"hostname": "payment-host-01",
"version": "1.2.3"
}
Log Level Guidelines
- DEBUG: Detailed information for debugging, typically disabled in production
- INFO: Routine information about normal operation
- WARN: Warning conditions that might require attention but don't indicate failure
- ERROR: Error conditions that indicate failure of a specific operation
- FATAL: Critical errors that cause application termination
Examples
# Configure logging levels by environment
npm run logging:configure -- --environment production --level WARN
# Analyze current logging implementation
npm run logging:analyze -- --path src/ --output logging-report.json
# Generate structured logging configuration
npm run logging:generate-config -- --format json --output logging-config.json
# Test logging output
npm run logging:test -- --scenario "payment-failure" --levels "ERROR,WARN"
# Validate logging best practices
npm run logging:validate -- --strict --check-pii --check-context
Output format
Logging Configuration Template:
logging:
level:
root: INFO
specific:
"com.example.service": DEBUG
"org.springframework": WARN
format:
type: json
timestamp_format: "ISO8601"
include_fields:
- timestamp
- level
- service
- component
- trace_id
- message
context:
auto_included:
- thread_id
- hostname
- service_version
propagated:
- trace_id
- user_id
- request_id
appenders:
- type: console
level: INFO
- type: file
path: /var/log/app.log
level: WARN
- type: http
endpoint: https://logs.example.com
level: ERROR
Logging Best Practices Report:
Logging Fundamentals Assessment
───────────────────────────────
Application: payment-service
Assessment Date: 2026-02-26
Score: 78/100
Strengths:
✅ Structured logging implemented (JSON format)
✅ Correlation IDs propagated across services
✅ Log levels appropriately configured
✅ PII filtering in place
Areas for Improvement:
⚠️ Insufficient context in error logs (missing user_id in 45% of error logs)
⚠️ Debug logs enabled in production for some components
⚠️ Inconsistent timestamp formats across services
⚠️ Missing business context in 30% of transaction logs
Critical Issues:
❌ No log sampling for high-volume debug logs
❌ Secret leakage detected in 2 log patterns
❌ Incomplete error context for 15% of database errors
Recommendations:
1. Implement consistent context inclusion middleware
2. Configure log sampling for debug-level logs
3. Add business context to all transaction logs
4. Update secret detection patterns
5. Standardize timestamp format across services
Implementation Priority:
- High: Fix secret leakage immediately
- Medium: Add missing context fields
- Low: Standardize timestamp format
Notes
- Structured logging is essential for modern log analysis and observability
- Context is more important than message content - ensure logs can be correlated
- Log levels should reflect operational importance, not developer convenience
- Consider log volume - too many logs can overwhelm systems and teams
- Test logging in production-like environments - logging behavior can differ
- Monitor your logging - ensure logs are being captured, processed, and stored
- Regularly review and update logging practices as systems evolve
- Balance human readability with machine parsability in log formats
- Document logging standards and ensure team adherence
- Consider the cost of logging - storage, processing, and analysis have expenses
1---2name: logging-fundamentals3description: Implement proper logging practices including log levels, structured logging, context propagation, and logging best practices for applications and systems4license: MIT5compatibility: opencode6metadata:7 audience: developers, SREs, DevOps engineers8 category: observability9---1011# Logging Fundamentals1213Establish proper logging practices including log levels, structured logging, context propagation, and comprehensive logging strategies for applications, services, and infrastructure.1415## When to use me1617Use this skill when:18- Setting up logging for new applications or services19- Reviewing existing logging implementations20- Establishing logging standards for teams or projects21- Debugging issues with incomplete or poor logging22- Implementing structured logging for better observability23- Configuring log levels and verbosity for different environments24- Ensuring logs contain sufficient context for troubleshooting2526## What I do2728### 1. Log Level Management29- **Define appropriate log levels** (DEBUG, INFO, WARN, ERROR, FATAL)30- **Configure level filtering** per environment (development, staging, production)31- **Implement dynamic level adjustment** without application restarts32- **Establish level usage guidelines** for different types of information33- **Create level-based alerting thresholds** for operational monitoring3435### 2. Structured Logging Implementation36- **Design log schema** with consistent field naming and types37- **Implement structured formats** (JSON, key-value pairs, structured text)38- **Include mandatory context fields** (timestamp, service, trace_id, user_id, etc.)39- **Handle nested structures and arrays** appropriately in logs40- **Ensure PII (Personally Identifiable Information) compliance** in log content4142### 3. Context Propagation43- **Implement correlation IDs** for request tracing across services44- **Propagate context through async operations** (queues, background jobs)45- **Maintain user/session context** throughout request lifecycle46- **Include business context** (order_id, transaction_id, etc.) in logs47- **Handle context in distributed systems** with proper header propagation4849### 4. Log Content Best Practices50- **Include sufficient context** for debugging without external systems51- **Balance detail with noise** - log enough but not too much52- **Use consistent message formats** across the codebase53- **Log before and after significant operations**54- **Include error details** (stack traces, error codes, recovery suggestions)55- **Avoid logging secrets, passwords, or sensitive data**5657### 5. Environment-Specific Configuration58- **Development logging** - Verbose, human-readable, local file output59- **Staging logging** - Balanced detail, structured format, aggregation60- **Production logging** - Minimal noise, structured only, remote aggregation61- **Debug mode logging** - Temporary increased verbosity for troubleshooting6263## Logging Principles6465### The 5 Ws of Logging661. **WHO** - Which user/service/process generated the log?672. **WHAT** - What action/event is being logged?683. **WHEN** - Precise timestamp with timezone information694. **WHERE** - Which component/function/file generated the log?705. **WHY** - What is the significance/severity of the logged event?7172### Structured Logging Fields73```json74{75 "timestamp": "2026-02-26T18:00:00Z",76 "level": "ERROR",77 "service": "payment-service",78 "component": "process_payment",79 "trace_id": "abc123-def456",80 "span_id": "def456",81 "user_id": "user-789",82 "session_id": "session-xyz",83 "request_id": "req-123456",84 "message": "Payment processing failed",85 "error_code": "PAYMENT_GATEWAY_TIMEOUT",86 "error_details": "Gateway response timeout after 5000ms",87 "stack_trace": "...",88 "context": {89 "order_id": "ord-987654",90 "amount": 99.99,91 "currency": "USD"92 },93 "duration_ms": 5123,94 "environment": "production",95 "hostname": "payment-host-01",96 "version": "1.2.3"97}98```99100### Log Level Guidelines101- **DEBUG**: Detailed information for debugging, typically disabled in production102- **INFO**: Routine information about normal operation103- **WARN**: Warning conditions that might require attention but don't indicate failure104- **ERROR**: Error conditions that indicate failure of a specific operation105- **FATAL**: Critical errors that cause application termination106107## Examples108109```bash110# Configure logging levels by environment111npm run logging:configure -- --environment production --level WARN112113# Analyze current logging implementation114npm run logging:analyze -- --path src/ --output logging-report.json115116# Generate structured logging configuration117npm run logging:generate-config -- --format json --output logging-config.json118119# Test logging output120npm run logging:test -- --scenario "payment-failure" --levels "ERROR,WARN"121122# Validate logging best practices123npm run logging:validate -- --strict --check-pii --check-context124```125126## Output format127128### Logging Configuration Template:129```yaml130logging:131 level: 132 root: INFO133 specific:134 "com.example.service": DEBUG135 "org.springframework": WARN136 137 format:138 type: json139 timestamp_format: "ISO8601"140 include_fields:141 - timestamp142 - level 143 - service144 - component145 - trace_id146 - message147 148 context:149 auto_included:150 - thread_id151 - hostname152 - service_version153 propagated:154 - trace_id155 - user_id156 - request_id157 158 appenders:159 - type: console160 level: INFO161 - type: file162 path: /var/log/app.log163 level: WARN164 - type: http165 endpoint: https://logs.example.com166 level: ERROR167```168169### Logging Best Practices Report:170```171Logging Fundamentals Assessment172───────────────────────────────173Application: payment-service174Assessment Date: 2026-02-26175Score: 78/100176177Strengths:178✅ Structured logging implemented (JSON format)179✅ Correlation IDs propagated across services180✅ Log levels appropriately configured181✅ PII filtering in place182183Areas for Improvement:184⚠️ Insufficient context in error logs (missing user_id in 45% of error logs)185⚠️ Debug logs enabled in production for some components186⚠️ Inconsistent timestamp formats across services187⚠️ Missing business context in 30% of transaction logs188189Critical Issues:190❌ No log sampling for high-volume debug logs191❌ Secret leakage detected in 2 log patterns192❌ Incomplete error context for 15% of database errors193194Recommendations:1951. Implement consistent context inclusion middleware1962. Configure log sampling for debug-level logs1973. Add business context to all transaction logs1984. Update secret detection patterns1995. Standardize timestamp format across services200201Implementation Priority:202- High: Fix secret leakage immediately203- Medium: Add missing context fields204- Low: Standardize timestamp format205```206207## Notes208209- **Structured logging is essential** for modern log analysis and observability210- **Context is more important than message content** - ensure logs can be correlated211- **Log levels should reflect operational importance**, not developer convenience212- **Consider log volume** - too many logs can overwhelm systems and teams213- **Test logging in production-like environments** - logging behavior can differ214- **Monitor your logging** - ensure logs are being captured, processed, and stored215- **Regularly review and update** logging practices as systems evolve216- **Balance human readability with machine parsability** in log formats217- **Document logging standards** and ensure team adherence218- **Consider the cost** of logging - storage, processing, and analysis have expenses