credit-tracing
v1.0.1
Published
Distributed tracing utility for credit node projects
Maintainers
Readme
credit-tracing
A distributed tracing utility for Credit Node.js projects based on OpenTelemetry with W3C Trace Context support and seamless integration with credit-logger.
Installation
npm install credit-tracingQuick Start
import express from 'express';
import { setupTracing } from 'credit-tracing';
const app = express();
// Set up tracing with a single line
const tracing = setupTracing({
serviceName: 'my-service',
defaultTenant: 'credit',
enableZipkin: true
});
// Add the integrated middleware
app.use(tracing.middleware);
// Define routes
app.get('/', (req, res) => {
// The trace context is automatically available in req.traceContext
res.json({
message: 'Hello World!',
traceInfo: req.traceContext
});
});
app.listen(3000);Detailed Usage
Basic Usage
import express from 'express';
import { initTracing, tracingMiddleware } from 'credit-tracing';
// Initialize tracing
const tracer = initTracing({
serviceName: 'user-service',
tenant: 'credit'
});
// Create Express app
const app = express();
// Add tracing middleware
app.use(tracingMiddleware(tracer));
// Routes
app.get('/users', (req, res) => {
// The request is already being traced
// You can access the trace context in req.traceContext
res.json({
users: [{ id: 1, name: 'John' }],
traceId: req.traceContext?.traceId
});
});
// Start the server
app.listen(3000, () => {
console.log('Server started on port 3000');
});Creating Custom Spans
import { getTracer } from 'credit-tracing';
// Get the tracer instance
const tracer = getTracer();
// Create a function with a span
function processData(data) {
return tracer.withSpan('processData', (span) => {
// Add custom attributes to the span
tracer.setSpanAttributes(span, {
'data.size': data.length,
'data.type': typeof data
});
// Your processing logic here
const result = data.map(item => item * 2);
return result;
});
}
// Create an async function with a span
async function fetchData(url) {
return tracer.withAsyncSpan('fetchData', async (span) => {
// Add custom attributes to the span
tracer.setSpanAttributes(span, {
'fetch.url': url
});
// Your async logic here
const response = await fetch(url);
const data = await response.json();
return data;
});
}Propagating Context Between Services
import axios from 'axios';
import { getTracer } from 'credit-tracing';
// Get the tracer instance
const tracer = getTracer();
async function callAnotherService(url) {
// Create headers object
const headers = {};
// Inject trace context into headers
tracer.injectTraceContext(headers);
// Make the request with trace context
const response = await axios.get(url, { headers });
return response.data;
}Configuration Options
| Option | Type | Default | Description | |--------|------|---------|-------------| | serviceName | string | 'application' | Name of the service | | tenant | string | 'default' | Tenant name | | samplingRate | number | 1.0 | Sampling rate (0.0 - 1.0) | | exporterUrl | string | 'http://localhost:4318/v1/traces' | OTLP exporter URL | | enableConsoleExporter | boolean | false | Whether to enable console exporter for debugging | | enableHttpInstrumentation | boolean | true | Whether to enable HTTP instrumentation | | enableExpressInstrumentation | boolean | true | Whether to enable Express instrumentation | | defaultAttributes | object | {} | Default attributes to add to all spans |
Integration with Logger
This tracing package works well with the credit-logger package. You can integrate them to include trace and span IDs in your logs:
import { createLogger } from 'credit-logger';
import { getTracer } from 'credit-tracing';
// Create a logger instance
const logger = createLogger({
applicationName: 'user-service',
tenant: 'credit'
});
// Get the tracer instance
const tracer = getTracer();
// In your request handler
app.get('/users', (req, res) => {
// Get the current trace context
const traceContext = tracer.getTraceContext();
// Log with trace context
logger.info('Processing users request', {
traceId: traceContext?.traceId,
spanId: traceContext?.spanId
});
// Rest of your handler
});License
ISC
