@deer-management-company/metrics-client
v1.0.0
Published
TypeScript client for the Metabase Self-Hosted Metrics API
Maintainers
Readme
@deer-management-company/metrics-client
TypeScript client for the Metabase Self-Hosted Metrics API. A powerful and type-safe SDK for collecting and sending metrics, job execution data, and API logs to your self-hosted monitoring infrastructure.
🚀 Installation
npm install @deer-management-company/metrics-client📋 Quick Start
import { MetricsClient } from '@deer-management-company/metrics-client';
// Initialize the client
const metricsClient = new MetricsClient({
baseUrl: 'http://your-metrics-api:3002',
apiKey: 'your-api-key',
serviceName: 'your-service-name',
environment: 'production'
});
// Record a job execution
await metricsClient.recordJob({
job_name: 'newsletter',
status: 'success',
total_results: 1250,
execution_time_ms: 45000,
metrics: {
qtd_save: 67,
qtd_rejected: 22
}
});
// Record API calls
await metricsClient.recordApiCall({
endpoint: '/api/users',
method: 'GET',
status_code: 200,
response_time_ms: 145
});
// Record performance metrics
await metricsClient.recordMetric({
metric_name: 'cpu_usage_percent',
metric_value: 45.6,
metric_type: 'gauge',
labels: {
instance: 'web-01'
}
});🔧 Express.js Integration
import express from 'express';
import { createMetricsMiddleware, createMetricsClient } from '@deer-management-company/metrics-client';
const app = express();
const metricsClient = createMetricsClient({
baseUrl: 'http://your-metrics-api:3002',
apiKey: 'your-api-key',
serviceName: 'express-api'
});
// Add metrics middleware
app.use(createMetricsMiddleware(metricsClient));
// Your routes here
app.get('/api/users', (req, res) => {
res.json({ users: [] });
});📊 Temporal Integration
Perfect for monitoring Temporal workflows:
import { MetricsClient } from '@deer-management-company/metrics-client';
@Workflow()
export class NewsletterWorkflow {
async runNewsletter(params: NewsletterParams): Promise<NewsletterResult> {
const metricsClient = new MetricsClient({
baseUrl: 'http://localhost:3002',
apiKey: process.env.METRICS_API_KEY!,
serviceName: 'temporal-newsletter'
});
const startTime = Date.now();
try {
const result = await Activity.runNewsletterActivity(params);
// Record successful execution
await metricsClient.recordJob({
job_name: 'newsletter',
status: 'success',
total_results: result.totalEmails,
execution_time_ms: Date.now() - startTime,
metrics: {
qtd_save: result.saved,
qtd_rejected: result.rejected,
qtd_sent: result.sent
}
});
return result;
} catch (error) {
// Record failure
await metricsClient.recordJob({
job_name: 'newsletter',
status: 'failed',
execution_time_ms: Date.now() - startTime,
error_message: error.message
});
throw error;
}
}
}📖 API Reference
MetricsClient
Constructor
new MetricsClient(config: MetricsClientConfig, options?: MetricsClientOptions)Methods
Job Tracking
recordJob(jobMetric: JobMetric)- Record job executiongetJobMetrics(jobName: string)- Get aggregated job metricsgetJobHistory(jobName: string, options?)- Get job execution history
API Monitoring
recordApiCall(apiLog: ApiLogData)- Record API callgetApiLogs(options?)- Get API call logs
Performance Metrics
recordMetric(metric: PerformanceMetric)- Record single metricrecordMetricsBatch(metrics: PerformanceMetric[])- Record multiple metrics
Utility Methods
healthCheck()- Check API healthgetServiceHealth()- Get service health statusgetSystemStatus()- Get overall system status
Metric Helpers
counter(name: string, labels?: object)- Create counter metricgauge(name: string, labels?: object)- Create gauge metrichistogram(name: string, labels?: object)- Create histogram metrictimeFunction(name: string, fn: Function, options?)- Time function execution
Configuration
interface MetricsClientConfig {
baseUrl: string; // API base URL
apiKey: string; // API authentication key
serviceName: string; // Your service identifier
timeout?: number; // Request timeout (default: 5000)
retries?: number; // Retry attempts (default: 3)
environment?: string; // Environment (default: 'production')
}
interface MetricsClientOptions {
timeout?: number; // Request timeout
retries?: number; // Retry attempts
retryDelay?: number; // Delay between retries
userAgent?: string; // Custom user agent
enableDebug?: boolean; // Enable debug logging
}Data Types
interface JobMetric {
job_name: string;
service_name: string;
user_name?: string;
status: 'success' | 'failed' | 'pending';
total_results?: number;
execution_time_ms?: number;
metrics?: Record<string, any>;
error_message?: string;
environment?: string;
}
interface ApiLogData {
service_name: string;
endpoint: string;
method: string;
status_code?: number;
response_time_ms?: number;
error_type?: string;
error_message?: string;
request_id?: string;
user_id?: string;
metadata?: Record<string, any>;
environment?: string;
}
interface PerformanceMetric {
service_name: string;
metric_name: string;
metric_value: number;
metric_type?: 'counter' | 'gauge' | 'histogram';
labels?: Record<string, any>;
}🎯 Use Cases
Newsletter Monitoring
// Track newsletter job execution
await metricsClient.recordJob({
job_name: 'newsletter',
status: 'success',
total_results: 1250,
execution_time_ms: 45000,
metrics: {
qtd_save: 67,
qtd_rejected: 22,
success_rate: 75.28
}
});API Performance Tracking
// Track API endpoint performance
await metricsClient.recordApiCall({
endpoint: '/api/v1/users',
method: 'GET',
status_code: 200,
response_time_ms: 145,
user_id: 'user123'
});System Metrics Collection
// Track system performance
await metricsClient.recordMetric({
metric_name: 'cpu_usage_percent',
metric_value: 45.6,
metric_type: 'gauge',
labels: {
instance: 'web-01',
region: 'us-east-1'
}
});🔗 Related Projects
- Metabase Self-Hosted - Complete monitoring solution
- Temporal - Workflow orchestration platform
🛠 Development
# Install dependencies
npm install
# Build the project
npm run build
# Run in development mode
npm run dev
# Run tests
npm run test
# Run linting
npm run lint
# Fix linting issues
npm run lint:fix📄 License
MIT License - see LICENSE file for details.
🤝 Contributing
Contributions welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Run linting and tests
- Submit a pull request
🐛 Issues
Found a bug? Please open an issue with:
- Description of the issue
- Steps to reproduce
- Expected vs actual behavior
- Environment details
Built with ❤️ by Deer Management Company
