Logging Best Practices
Learn how to structure logs for effective debugging and analysis.
Log Levels
Use the appropriate log level to categorize your logs:
debug
Detailed information for debugging. Not shown in production by default.
client.debug('Cache lookup', { key: 'user:123', hit: false });info
General information about application flow. Normal operations.
client.info('User logged in', { userId: '123', method: 'oauth' });warn
Something unexpected happened but the application continues. Worth investigating.
client.warn('Rate limit approaching', { current: 95, limit: 100 });error
Something failed. Requires attention. Include error details and context.
client.error('Payment failed', { orderId: '456', error: 'Card declined' });Structured Metadata
Always include relevant context in your log metadata:
// Good: Structured metadata for easy querying
client.info('Order processed', {
orderId: 'ord_123',
userId: 'user_456',
total: 99.99,
items: 3,
paymentMethod: 'stripe',
});
// Bad: Unstructured message
client.info('Order ord_123 for user_456 processed for $99.99');Error Tracking
Use trackError to capture full error details including stack traces:
try {
await processPayment(orderId);
} catch (error) {
// trackError captures: message, stack, name
client.trackError(error, {
orderId,
userId: currentUser.id,
paymentProvider: 'stripe',
});
// Also log for immediate visibility
client.error('Payment processing failed', {
orderId,
error: error.message,
});
}Version Correlation
All logs automatically include session ID and version info for correlation:
// Set versions once
client.setFrontendVersion({ version: '1.2.0', commit: 'abc123' });
client.setBackendVersion({ version: '2.1.0', commit: 'def456' });
// All subsequent logs include version info
client.error('API call failed', { endpoint: '/api/users' });
// In dashboard, you can filter:
// - All errors from frontend v1.2.0
// - All errors from backend v2.1.0
// - All events from this specific sessionBest Practices
Use consistent naming
Use snake_case for event names and camelCase for metadata keys consistently.
Include IDs, not names
Log user IDs, order IDs, and other identifiers rather than names for easy querying.
Avoid sensitive data
Never log passwords, tokens, credit card numbers, or PII.
Flush before exit
In Node.js, call await client.flush() before process exit to ensure all logs are sent.