@aleph-alpha/lib-telemetry
v0.11.134
Published
Telemetry service for frontend applications
Readme
Telemetry Library
A framework-agnostic telemetry library for frontend applications that supports multiple telemetry backends (Faro and OpenTelemetry) using a plugin-first approach. Designed for vendor neutrality with automatic endpoint testing and graceful fallbacks.
Installation
pnpm add @aleph-alpha/lib-telemetry
# or
npm install @aleph-alpha/lib-telemetry
# or
yarn add @aleph-alpha/lib-telemetryQuick Start
Vue.js Plugin Setup (Recommended)
import { createApp } from 'vue';
import { TelemetryVuePlugin, FaroTelemetryPlugin } from '@aleph-alpha/lib-telemetry';
import App from './App.vue';
const app = createApp(App);
// Setup with Faro plugin
app.use(TelemetryVuePlugin,
FaroTelemetryPlugin({
url: 'https://faro-collector.example.com',
apiKey: 'your-api-key',
appName: 'my-app',
appVersion: '1.0.0',
environment: 'production',
debug: true
})
);
app.mount('#app');Alternative: OpenTelemetry Plugin
import { TelemetryVuePlugin, OtelTelemetryPlugin } from '@aleph-alpha/lib-telemetry';
app.use(TelemetryVuePlugin,
OtelTelemetryPlugin({
otlpUrl: 'http://localhost:4318/v1/traces',
appName: 'my-app',
appVersion: '1.0.0'
})
);Global Telemetry Instance
import { telemetry } from '@aleph-alpha/lib-telemetry';
// Access the global telemetry proxy (automatically updates when Vue plugin initializes)
telemetry.addEvent('user_action', { action: 'click', element: 'button' });
telemetry.recordException(new Error('Something went wrong'));
telemetry.setUser({ id: '123', email: '[email protected]' });
// Session baggage for request correlation
telemetry.setUserSessionBaggage('user-123', 'session-456');
telemetry.setSessionBaggageFeatureFlags(['new-ui', 'beta-features']);Vue.js Integration
Plugin Setup
// main.ts
import { createApp } from 'vue';
import { TelemetryVuePlugin, FaroTelemetryPlugin } from '@aleph-alpha/lib-telemetry';
import App from './App.vue';
const app = createApp(App);
// Faro plugin setup
app.use(TelemetryVuePlugin,
FaroTelemetryPlugin({
url: 'https://faro-collector.example.com',
apiKey: 'your-api-key',
appName: 'my-app',
appVersion: '1.0.0',
environment: 'production',
debug: true
})
);
app.mount('#app');OpenTelemetry Plugin Setup
import { TelemetryVuePlugin, OtelTelemetryPlugin } from '@aleph-alpha/lib-telemetry';
app.use(TelemetryVuePlugin,
OtelTelemetryPlugin({
otlpUrl: 'http://localhost:4318/v1/traces',
appName: 'my-app',
appVersion: '1.0.0'
})
);No Telemetry (Development/Testing)
import { TelemetryVuePlugin } from '@aleph-alpha/lib-telemetry';
// Uses NoTelemetryPlugin by default when no plugin is provided
app.use(TelemetryVuePlugin);Usage in Components
<template>
<div>
<button @click="trackButtonClick">Click me</button>
</div>
</template>
<script setup lang="ts">
import { useTelemetry } from '@aleph-alpha/lib-telemetry';
const telemetry = useTelemetry();
function trackButtonClick() {
telemetry.addEvent('button_clicked', {
component: 'MyComponent',
timestamp: Date.now()
});
}
// Set user context when user data becomes available
telemetry.setUser({
id: 'user-123',
email: '[email protected]'
});
</script>Automatic Features
Endpoint Testing & Fallbacks
The library automatically:
- Tests endpoint accessibility during Vue plugin initialization
- Falls back to NoTelemetryPlugin if endpoints are blocked by privacy tools
- Handles network errors gracefully
- Provides meaningful console warnings
Browser Privacy Protection
Automatically detects and handles:
- Brave Shields blocking
- uBlock Origin filtering
- Network-level blocking
- CORS restrictions
Configuration Options
Plugin Configuration
All plugins now include application-level configuration directly:
// Faro Plugin Options
FaroTelemetryPlugin({
url: string; // Faro collector URL (required)
apiKey?: string; // Faro API key (optional)
appName?: string; // App name (default: 'telemetry-lib')
appVersion?: string; // App version (default: '1.0.0')
environment?: string; // Environment (default: 'development')
debug?: boolean; // Debug mode (default: false)
includeBaggageUrls?: string[]; // URL patterns to include for baggage (allowlist)
excludeBaggageUrls?: string[]; // URL patterns to exclude from baggage (blocklist)
})
// OpenTelemetry Plugin Options
OtelTelemetryPlugin({
otlpUrl: string; // OTLP endpoint URL (required)
appName?: string; // App name (default: 'telemetry-lib')
appVersion?: string; // App version (default: '1.0.0')
environment?: string; // Environment (default: 'development')
debug?: boolean; // Debug mode (default: false)
includeBaggageUrls?: string[]; // URL patterns to include for baggage (allowlist)
excludeBaggageUrls?: string[]; // URL patterns to exclude from baggage (blocklist)
})Baggage URL Filtering
Control which URLs receive baggage headers for cross-request correlation:
// Example: Only internal APIs, but exclude auth endpoints
FaroTelemetryPlugin({
url: 'https://faro.example.com',
includeBaggageUrls: [/.*\.pharia\.com/], // Allowlist: only pharia.com domains
excludeBaggageUrls: [/.*iam\.pharia\.com/] // Blocklist: exclude IAM subdomain
})Vue Plugin Usage
The Vue plugin now takes a configured telemetry plugin directly:
// Pass a fully configured plugin
app.use(TelemetryVuePlugin, configuredPlugin);
// Or use default NoTelemetryPlugin
app.use(TelemetryVuePlugin);API Reference
Core Functions
telemetry: Global telemetry instance proxy (automatically updates when TelemetryVuePlugin initializes)
Telemetry Instance Methods
interface TelemetryInstance {
// Lifecycle
init(): void;
flush(): Promise<void>;
// Events & Exceptions
addEvent(name: string, attributes?: Record<string, any>): void;
recordException(error: Error, context?: Record<string, any>): void;
// User & Attributes
setUser(user: { id: string; email?: string; [key: string]: any }): void;
setAttribute(key: string, value: string | number | boolean): void;
// Baggage (Cross-request correlation)
setBaggage(key: string, value: string, scope?: 'request' | 'session'): void;
setUserSessionBaggage(userId: string, sessionId: string): void;
setSessionBaggageFeatureFlags(flags: string[]): void;
// Spans (OpenTelemetry)
startSpan(name: string, attributes?: Record<string, any>): any;
}Vue Composables
useTelemetry(): Access telemetry instance in Vue components
Migration Notes
The library uses a simplified plugin-first approach where you pass a fully configured telemetry plugin directly:
import { TelemetryVuePlugin, FaroTelemetryPlugin } from '@aleph-alpha/lib-telemetry';
app.use(TelemetryVuePlugin,
FaroTelemetryPlugin({
url: 'https://faro-collector.example.com',
apiKey: 'your-api-key',
appName: 'my-app',
appVersion: '1.0.0',
environment: 'production'
})
);Key Changes:
- Simplified Interface: No more config objects - pass configured plugins directly
- Self-Contained Plugins: All configuration (app name, version, environment) is included in the plugin
- Consistent API:
TelemetryVuePluginandtelemetryboth accept plugins the same way - Breaking Change: The old
{ plugin: ..., appName: ... }interface is removed
Migration Steps:
- Move
appName,appVersion,environment, anddebuginto your plugin configuration - Pass the configured plugin directly to
TelemetryVuePlugin - Remove the wrapping config object
Testing
Running Tests
# Run all tests
pnpm test
# Run specific test suites
pnpm test telemetry
pnpm test TelemetryVuePlugin
# Run tests with watch mode
pnpm test:watchWith Nx (from workspace root)
npx nx test lib-telemetry # All tests
npx nx test:unit lib-telemetry # Unit tests onlyDevelopment
Local Development with Live Reload
In the package directory:
pnpm run dev # Starts tsup in watch modeLink the package globally:
pnpm link --globalIn your app directory:
pnpm link --global @aleph-alpha/lib-telemetryEdit and see changes immediately - tsup rebuilds on file changes
Build & Quality Checks
pnpm typecheck # TypeScript compilation check
pnpm build # Build the package
pnpm test # Run testsDocumentation
Additional documentation is available in the /docs directory:
Core Architecture Documentation
- Request Span Attributes & Request Scope - Detailed explanation of our attribute injection approach, request-scoped attributes lifecycle, GenAI convenience functions, and HTTP auto-instrumentation integration
- Baggage Implementation Summary - Comprehensive guide to baggage system architecture, cross-request correlation, session vs request scope, and OpenTelemetry compliance
Documentation Organization
- README.md (this file) - Quick start, installation, basic usage examples, and API overview
- REQUEST_SPAN_ATTRIBUTES.md - Technical deep dive into attribute injection approach and request scope
- BAGGAGE_IMPLEMENTATION_SUMMARY.md - Comprehensive baggage system architecture and implementation details
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate and follow the existing code style.
Key Features
Attribute Injection Approach
Instead of creating custom spans, our library injects attributes into auto-instrumented HTTP spans. This provides convenience while leveraging OpenTelemetry's existing auto-instrumentation for fetch and XMLHttpRequest.
GenAI Support
Built-in support for GenAI operations with convenience functions that automatically set OpenTelemetry GenAI semantic conventions:
import { setChatOperation } from '@aleph-alpha/lib-telemetry';
// Set GenAI attributes before making API call
setChatOperation('pharia_qa_chat', 'conv-123', 'luminous-supreme');
const response = await fetch('/api/chat', { /* ... */ });
// Span automatically gets gen_ai.operation.name, gen_ai.agent.id, etc.Cross-Request Correlation
Automatic baggage propagation for session and request-level context:
// Session-level context (persists across requests)
telemetry.setUserSessionBaggage('user-123', 'session-456');
// Request-level context (cleared after request)
telemetry.setBaggage('conversation.id', 'conv-123', BaggageScope.REQUEST);Learn More:
Available Exports
The library exports the following modules for different use cases:
Core Functions
import {
telemetry, // Global telemetry instance proxy
TelemetryVuePlugin, // Vue.js plugin
useTelemetry // Vue composable
} from '@aleph-alpha/lib-telemetry';GenAI Utilities
import {
setGenAiSpan, // Set GenAI operation attributes
setGenAiContext, // Set GenAI context baggage
setChatOperation, // Chat operation convenience function
setEmbeddingsOperation, // Embeddings operation convenience function
setToolExecutionOperation, // Tool execution convenience function
setAgentCreationOperation, // Agent creation convenience function
setAgentInvocationOperation, // Agent invocation convenience function
setTextCompletionOperation, // Text completion convenience function
setGenerateContentOperation // Content generation convenience function
} from '@aleph-alpha/lib-telemetry';Direct Plugin Access
import {
FaroTelemetryPlugin, // Faro telemetry plugin
OtelTelemetryPlugin // OpenTelemetry plugin
} from '@aleph-alpha/lib-telemetry';OpenTelemetry Utilities
import {
SpanKind, // OpenTelemetry span types
context, // OpenTelemetry context API
BAGGAGE_KEYS, // Standard baggage key constants
APP_BAGGAGE_KEYS, // GenAI-specific baggage keys
APP_SPAN_ATTRIBUTE_VALUES // GenAI operation constants
} from '@aleph-alpha/lib-telemetry';Types
import type {
TelemetryConfig, // Configuration interface (internal use)
TelemetryInstance, // Telemetry instance interface
BaggageScope // Baggage scope enumeration
} from '@aleph-alpha/lib-telemetry';