Cloudflare Workers Observability
Production-grade observability for Cloudflare Workers: logging, metrics, tracing, and alerting.
Quick Start
// Structured logging with context
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const requestId = crypto.randomUUID();
const logger = createLogger(requestId, env);
try {
logger.info('Request received', { method: request.method, url: request.url });
const result = await handleRequest(request, env);
logger.info('Request completed', { status: result.status });
return result;
} catch (error) {
logger.error('Request failed', { error: error.message, stack: error.stack });
throw error;
}
}
};
// Simple logger factory
function createLogger(requestId: string, env: Env) {
return {
info: (msg: string, data?: object) => console.log(JSON.stringify({ level: 'info', requestId, msg, ...data, timestamp: Date.now() })),
error: (msg: string, data?: object) => console.error(JSON.stringify({ level: 'error', requestId, msg, ...data, timestamp: Date.now() })),
warn: (msg: string, data?: object) => console.warn(JSON.stringify({ level: 'warn', requestId, msg, ...data, timestamp: Date.now() })),
};
}
Critical Rules
- Always use structured JSON logging - Plain text logs are hard to parse and aggregate
- Include request context - Request ID, method, path in every log entry
- Never log sensitive data - Redact tokens, passwords, PII from logs
- Use appropriate log levels - ERROR for failures, WARN for recoverable issues, INFO for operations
- Sample high-volume logs - Use 1-10% sampling for request logs in production
Observability Components
| Component |
Purpose |
When to Use |
console.log |
Basic logging |
Development, debugging |
| Tail Workers |
Real-time log streaming |
Production log aggregation |
| Analytics Engine |
Custom metrics/analytics |
Business metrics, performance tracking |
| Logpush |
Log export to external services |
Long-term storage, compliance |
| Workers Trace Events |
Distributed tracing |
Request flow debugging |
Top 8 Errors Prevented
| Error |
Symptom |
Prevention |
| Logs not appearing |
No output in dashboard |
Enable "Standard" logging in wrangler.jsonc |
| Log truncation |
Messages cut off at 128KB |
Chunk large payloads, use sampling |
| Tail Worker not receiving |
No events processed |
Check binding name matches wrangler.jsonc |
| Analytics Engine write fails |
Data not recorded |
Verify AE binding, check blobs format |
| PII in logs |
Security/compliance violation |
Implement redaction middleware |
| Missing request context |
Can't correlate logs |
Add requestId to all log entries |
| Log volume explosion |
High costs, noise |
Implement sampling for high-frequency events |
| Alerting gaps |
Incidents not detected |
Configure monitors for error rate thresholds |
Logging Configuration
wrangler.jsonc:
{
"name": "my-worker",
"observability": {
"enabled": true,
"head_sampling_rate": 1 // 0-1, 1 = 100% of requests
},
"tail_consumers": [
{
"service": "log-aggregator", // Tail Worker name
"environment": "production"
}
],
"analytics_engine_datasets": [
{
"binding": "ANALYTICS",
"dataset": "my_worker_metrics"
}
]
}
Structured Logging Pattern
interface LogEntry {
level: 'debug' | 'info' | 'warn' | 'error';
message: string;
requestId: string;
timestamp: number;
// Contextual data
method?: string;
path?: string;
status?: number;
duration?: number;
// Error details
error?: {
name: string;
message: string;
stack?: string;
};
// Custom fields
[key: string]: unknown;
}
class Logger {
constructor(private requestId: string, private baseContext: object = {}) {}
private log(level: LogEntry['level'], message: string, data?: object) {
const entry: LogEntry = {
level,
message,
requestId: this.requestId,
timestamp: Date.now(),
...this.baseContext,
...data,
};
// Redact sensitive fields
const sanitized = this.redact(entry);
const output = JSON.stringify(sanitized);
level === 'error' ? console.error(output) : console.log(output);
}
private redact(entry: LogEntry): LogEntry {
const sensitiveKeys = ['password', 'token', 'secret', 'authorization', 'cookie'];
const redacted = { ...entry };
for (const key of Object.keys(redacted)) {
if (sensitiveKeys.some(s => key.toLowerCase().includes(s))) {
redacted[key] = '[REDACTED]';
}
}
return redacted;
}
info(message: string, data?: object) { this.log('info', message, data); }
warn(message: string, data?: object) { this.log('warn', message, data); }
error(message: string, data?: object) { this.log('error', message, data); }
debug(message: string, data?: object) { this.log('debug', message, data); }
}
Analytics Engine Usage
interface Env {
ANALYTICS: AnalyticsEngineDataset;
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const start = Date.now();
const url = new URL(request.url);
try {
const response = await handleRequest(request, env);
// Write success metric
env.ANALYTICS.writeDataPoint({
blobs: [request.method, url.pathname, String(response.status)],
doubles: [Date.now() - start], // Response time in ms
indexes: [url.pathname.split('/')[1] || 'root'], // Index for fast queries
});
return response;
} catch (error) {
// Write error metric
env.ANALYTICS.writeDataPoint({
blobs: [request.method, url.pathname, 'error', error.message],
doubles: [Date.now() - start],
indexes: ['error'],
});
throw error;
}
}
};
Tail Worker Pattern
// tail-worker.ts - Receives logs from other workers
interface TailEvent {
scriptName: string;
event: {
request?: { method: string; url: string };
response?: { status: number };
};
logs: Array<{
level: string;
message: unknown[];
timestamp: number;
}>;
exceptions: Array<{
name: string;
message: string;
timestamp: number;
}>;
outcome: 'ok' | 'exception' | 'exceededCpu' | 'exceededMemory' | 'canceled';
eventTimestamp: number;
}
export default {
async tail(events: TailEvent[], env: Env): Promise<void> {
for (const event of events) {
// Filter and forward logs
const errorLogs = event.logs.filter(l => l.level === 'error');
const exceptions = event.exceptions;
if (errorLogs.length > 0 || exceptions.length > 0) {
// Send to external logging service
await fetch(env.LOGGING_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
scriptName: event.scriptName,
timestamp: event.eventTimestamp,
errors: errorLogs,
exceptions,
outcome: event.outcome,
}),
});
}
}
}
};
When to Load References
Load specific references based on the task:
- Setting up logging? → Load
references/logging.md for structured logging patterns, log levels, redaction
- Building custom metrics? → Load
references/analytics-engine.md for Analytics Engine SQL queries, data modeling
- Implementing log aggregation? → Load
references/tail-workers.md for Tail Worker patterns, external service integration
- Creating dashboards/tracking? → Load
references/custom-metrics.md for business metrics, performance tracking
- Setting up alerts? → Load
references/alerting.md for error rate monitoring, PagerDuty/Slack integration
Templates
| Template |
Purpose |
Use When |
templates/logging-setup.ts |
Production logging class |
Setting up new worker with logging |
templates/analytics-worker.ts |
Analytics Engine integration |
Adding custom metrics |
templates/tail-worker.ts |
Complete Tail Worker |
Building log aggregation pipeline |
Scripts
| Script |
Purpose |
Command |
scripts/setup-logging.sh |
Configure logging settings |
./setup-logging.sh |
scripts/analyze-logs.sh |
Query and analyze logs |
./analyze-logs.sh --errors --last 1h |
Resources
1---2name: cloudflare-workers-observability3description: Cloudflare Workers observability with logging, Analytics Engine, Tail Workers, metrics, and alerting. Use for monitoring, debugging, tracing, or encountering log parsing, metric aggregation, alert configuration errors.4license: MIT5metadata:6 source: https://skillmd.com/skills/secondsky/cloudflare-workers-observability7---89# Cloudflare Workers Observability1011Production-grade observability for Cloudflare Workers: logging, metrics, tracing, and alerting.1213## Quick Start1415```typescript16// Structured logging with context17export default {18 async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {19 const requestId = crypto.randomUUID();20 const logger = createLogger(requestId, env);2122 try {23 logger.info('Request received', { method: request.method, url: request.url });2425 const result = await handleRequest(request, env);2627 logger.info('Request completed', { status: result.status });28 return result;29 } catch (error) {30 logger.error('Request failed', { error: error.message, stack: error.stack });31 throw error;32 }33 }34};3536// Simple logger factory37function createLogger(requestId: string, env: Env) {38 return {39 info: (msg: string, data?: object) => console.log(JSON.stringify({ level: 'info', requestId, msg, ...data, timestamp: Date.now() })),40 error: (msg: string, data?: object) => console.error(JSON.stringify({ level: 'error', requestId, msg, ...data, timestamp: Date.now() })),41 warn: (msg: string, data?: object) => console.warn(JSON.stringify({ level: 'warn', requestId, msg, ...data, timestamp: Date.now() })),42 };43}44```4546## Critical Rules47481. **Always use structured JSON logging** - Plain text logs are hard to parse and aggregate492. **Include request context** - Request ID, method, path in every log entry503. **Never log sensitive data** - Redact tokens, passwords, PII from logs514. **Use appropriate log levels** - ERROR for failures, WARN for recoverable issues, INFO for operations525. **Sample high-volume logs** - Use 1-10% sampling for request logs in production5354## Observability Components5556| Component | Purpose | When to Use |57|-----------|---------|-------------|58| `console.log` | Basic logging | Development, debugging |59| **Tail Workers** | Real-time log streaming | Production log aggregation |60| **Analytics Engine** | Custom metrics/analytics | Business metrics, performance tracking |61| **Logpush** | Log export to external services | Long-term storage, compliance |62| **Workers Trace Events** | Distributed tracing | Request flow debugging |6364## Top 8 Errors Prevented6566| Error | Symptom | Prevention |67|-------|---------|------------|68| Logs not appearing | No output in dashboard | Enable "Standard" logging in wrangler.jsonc |69| Log truncation | Messages cut off at 128KB | Chunk large payloads, use sampling |70| Tail Worker not receiving | No events processed | Check binding name matches wrangler.jsonc |71| Analytics Engine write fails | Data not recorded | Verify AE binding, check blobs format |72| PII in logs | Security/compliance violation | Implement redaction middleware |73| Missing request context | Can't correlate logs | Add requestId to all log entries |74| Log volume explosion | High costs, noise | Implement sampling for high-frequency events |75| Alerting gaps | Incidents not detected | Configure monitors for error rate thresholds |7677## Logging Configuration7879**wrangler.jsonc**:80```jsonc81{82 "name": "my-worker",83 "observability": {84 "enabled": true,85 "head_sampling_rate": 1 // 0-1, 1 = 100% of requests86 },87 "tail_consumers": [88 {89 "service": "log-aggregator", // Tail Worker name90 "environment": "production"91 }92 ],93 "analytics_engine_datasets": [94 {95 "binding": "ANALYTICS",96 "dataset": "my_worker_metrics"97 }98 ]99}100```101102## Structured Logging Pattern103104```typescript105interface LogEntry {106 level: 'debug' | 'info' | 'warn' | 'error';107 message: string;108 requestId: string;109 timestamp: number;110 // Contextual data111 method?: string;112 path?: string;113 status?: number;114 duration?: number;115 // Error details116 error?: {117 name: string;118 message: string;119 stack?: string;120 };121 // Custom fields122 [key: string]: unknown;123}124125class Logger {126 constructor(private requestId: string, private baseContext: object = {}) {}127128 private log(level: LogEntry['level'], message: string, data?: object) {129 const entry: LogEntry = {130 level,131 message,132 requestId: this.requestId,133 timestamp: Date.now(),134 ...this.baseContext,135 ...data,136 };137138 // Redact sensitive fields139 const sanitized = this.redact(entry);140141 const output = JSON.stringify(sanitized);142 level === 'error' ? console.error(output) : console.log(output);143 }144145 private redact(entry: LogEntry): LogEntry {146 const sensitiveKeys = ['password', 'token', 'secret', 'authorization', 'cookie'];147 const redacted = { ...entry };148149 for (const key of Object.keys(redacted)) {150 if (sensitiveKeys.some(s => key.toLowerCase().includes(s))) {151 redacted[key] = '[REDACTED]';152 }153 }154 return redacted;155 }156157 info(message: string, data?: object) { this.log('info', message, data); }158 warn(message: string, data?: object) { this.log('warn', message, data); }159 error(message: string, data?: object) { this.log('error', message, data); }160 debug(message: string, data?: object) { this.log('debug', message, data); }161}162```163164## Analytics Engine Usage165166```typescript167interface Env {168 ANALYTICS: AnalyticsEngineDataset;169}170171export default {172 async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {173 const start = Date.now();174 const url = new URL(request.url);175176 try {177 const response = await handleRequest(request, env);178179 // Write success metric180 env.ANALYTICS.writeDataPoint({181 blobs: [request.method, url.pathname, String(response.status)],182 doubles: [Date.now() - start], // Response time in ms183 indexes: [url.pathname.split('/')[1] || 'root'], // Index for fast queries184 });185186 return response;187 } catch (error) {188 // Write error metric189 env.ANALYTICS.writeDataPoint({190 blobs: [request.method, url.pathname, 'error', error.message],191 doubles: [Date.now() - start],192 indexes: ['error'],193 });194 throw error;195 }196 }197};198```199200## Tail Worker Pattern201202```typescript203// tail-worker.ts - Receives logs from other workers204interface TailEvent {205 scriptName: string;206 event: {207 request?: { method: string; url: string };208 response?: { status: number };209 };210 logs: Array<{211 level: string;212 message: unknown[];213 timestamp: number;214 }>;215 exceptions: Array<{216 name: string;217 message: string;218 timestamp: number;219 }>;220 outcome: 'ok' | 'exception' | 'exceededCpu' | 'exceededMemory' | 'canceled';221 eventTimestamp: number;222}223224export default {225 async tail(events: TailEvent[], env: Env): Promise<void> {226 for (const event of events) {227 // Filter and forward logs228 const errorLogs = event.logs.filter(l => l.level === 'error');229 const exceptions = event.exceptions;230231 if (errorLogs.length > 0 || exceptions.length > 0) {232 // Send to external logging service233 await fetch(env.LOGGING_ENDPOINT, {234 method: 'POST',235 headers: { 'Content-Type': 'application/json' },236 body: JSON.stringify({237 scriptName: event.scriptName,238 timestamp: event.eventTimestamp,239 errors: errorLogs,240 exceptions,241 outcome: event.outcome,242 }),243 });244 }245 }246 }247};248```249250## When to Load References251252Load specific references based on the task:253254- **Setting up logging?** → Load `references/logging.md` for structured logging patterns, log levels, redaction255- **Building custom metrics?** → Load `references/analytics-engine.md` for Analytics Engine SQL queries, data modeling256- **Implementing log aggregation?** → Load `references/tail-workers.md` for Tail Worker patterns, external service integration257- **Creating dashboards/tracking?** → Load `references/custom-metrics.md` for business metrics, performance tracking258- **Setting up alerts?** → Load `references/alerting.md` for error rate monitoring, PagerDuty/Slack integration259260## Templates261262| Template | Purpose | Use When |263|----------|---------|----------|264| `templates/logging-setup.ts` | Production logging class | Setting up new worker with logging |265| `templates/analytics-worker.ts` | Analytics Engine integration | Adding custom metrics |266| `templates/tail-worker.ts` | Complete Tail Worker | Building log aggregation pipeline |267268## Scripts269270| Script | Purpose | Command |271|--------|---------|---------|272| `scripts/setup-logging.sh` | Configure logging settings | `./setup-logging.sh` |273| `scripts/analyze-logs.sh` | Query and analyze logs | `./analyze-logs.sh --errors --last 1h` |274275## Resources276277- Workers Observability: https://developers.cloudflare.com/workers/observability/278- Analytics Engine: https://developers.cloudflare.com/analytics/analytics-engine/279- Tail Workers: https://developers.cloudflare.com/workers/observability/tail-workers/280- Logpush: https://developers.cloudflare.com/logs/get-started/