### Setting up Zipkin GRPC Client Interceptor in Node.js Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-grpc-client/README.md This comprehensive example demonstrates the full setup process for integrating Zipkin tracing with a gRPC client using the zipkin-instrumentation-grpc-client library. It includes setting up the Zipkin tracer, loading the protobuf definition, creating the gRPC client, and initializing the interceptor before making a traced client call. ```javascript const grpc = require('grpc'); const protoLoader = require('@grpc/proto-loader'); const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const grpcInstrumentation = require('zipkin-instrumentation-grpc-client'); const PROTO_PATH = __dirname + '/protos/weather.proto'; const PROTO_OPTIONS = { keepCase: true, enums: String, defaults: true, oneofs: true }; // setup zipkin tracer const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); // setup grpc client const definition = protoLoader.loadSync(PROTO_PATH, PROTO_OPTIONS); const weather = grpc.loadPackageDefinition(definition).weather; const client = new weather.WeatherService('localhost:50051', grpc.credentials.createInsecure()); //setup interceptor const remoteServiceName = 'weather-service'; const interceptor = grpcInstrumentation(grpc, {tracer, remoteServiceName}); client.getTemperature({ location: 'Tahoe'}, { interceptors: [interceptor] }, (error, response) => { console.info(`temprature in Tahoe is: ${response.temperature} `); }); ``` -------------------------------- ### Setup Development Environment Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md Runs the `yarn` command to install project dependencies and set up the monorepo development environment using Lerna. ```bash yarn ``` -------------------------------- ### Basic Zipkin Tracer Setup with HTTP Transport Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md Demonstrates the basic setup for a Zipkin tracer using `CLSContext` for implicit context propagation, `BatchRecorder` with `HttpLogger` for sending spans to a Zipkin collector, and shows how to instrument `fetch`. ```JavaScript const { Tracer, BatchRecorder, jsonEncoder: {JSON_V2} } = require('zipkin'); const CLSContext = require('zipkin-context-cls'); const {HttpLogger} = require('zipkin-transport-http'); // Setup the tracer const tracer = new Tracer({ ctxImpl: new CLSContext('zipkin'), // implicit in-process context recorder: new BatchRecorder({ logger: new HttpLogger({ endpoint: 'http://localhost:9411/api/v2/spans', jsonEncoder: JSON_V2 }) }), // batched http recorder localServiceName: 'service-a' // name of this application }); // now use tracer to construct instrumentation! For example, fetch const wrapFetch = require('zipkin-instrumentation-fetch'); const remoteServiceName = 'youtube'; // name of the application that // will be called (optional) const zipkinFetch = wrapFetch(fetch, {tracer, remoteServiceName}); ``` -------------------------------- ### Wrap Default Axios Instance and Perform GET Request Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-axiosjs/README.md Demonstrates how to wrap the default axios instance with Zipkin tracing and perform a GET request. It shows the setup for Zipkin tracer, context, and recorder. ```javascript const axios = require('axios'); const wrapAxios = require('zipkin-instrumentation-axiosjs'); const { Tracer, ExplicitContext, ConsoleRecorder } = require('zipkin'); const ctxImpl = new ExplicitContext(); // the in-process context const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ ctxImpl, recorder, localServiceName }); const remoteServiceName = 'weather-api'; // name of the application you are // calling (optional) const zipkinAxios = wrapAxios(axios, { tracer, remoteServiceName }); zipkinAxios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` -------------------------------- ### Initializing Zipkin HTTP Transport and Tracer (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-transport-http/README.md Demonstrates the basic setup for sending Zipkin spans over HTTP using `zipkin-transport-http`. It shows how to create a `BatchRecorder` with `HttpLogger` configured with an endpoint and other optional parameters, and then how to initialize a `Tracer` using this recorder. ```javascript const { Tracer, BatchRecorder, jsonEncoder: {JSON_V2} } = require('zipkin'); const {HttpLogger} = require('zipkin-transport-http'); const noop = require('noop-logger'); const recorder = new BatchRecorder({ logger: new HttpLogger({ endpoint: 'http://localhost:9411/api/v2/spans', // Required jsonEncoder: JSON_V2, // JSON encoder to use. Optional (defaults to JSON_V1) httpInterval: 1000, // How often to sync spans. Optional (defaults to 1000) headers: {'Authorization': 'secret'}, // Custom HTTP headers. Optional timeout: 1000, // Timeout for HTTP Post. Optional (defaults to 0) maxPayloadSize: 0, // Max payload size for zipkin span. Optional (defaults to 0) agent: new http.Agent({keepAlive: true}), // Agent used for network related options. Optional (defaults to null) log: noop, // Logger to use. Optional (defaults to console) fetchImplementation: require('node-fetch') // Pluggable fetch implementation (defaults to global fetch or fallsback to node fetch) }) }); const tracer = new Tracer({ recorder, ctxImpl, // this would typically be a CLSContext or ExplicitContext localServiceName: 'service-a' // name of this application }); ``` -------------------------------- ### Initializing and Using zipkin-instrumentation-memcached Client Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-memcached/README.md This snippet demonstrates how to initialize the zipkin-instrumentation-memcached library to wrap a standard Memcached client. It requires the 'zipkin', 'memcached', and 'zipkin-instrumentation-memcached' packages. The code sets up a Zipkin tracer and then wraps the Memcached client constructor before creating an instance, showing a basic 'get' operation. ```javascript const {Tracer} = require('zipkin'); const Memcached = require('memcached'); const zipkinClient = require('zipkin-instrumentation-memcached'); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const connectionString = ''localhost:11211''; const options = {timeout: 1000}; const memcached = new (zipkinClient(tracer, Memcached))(connectionString, options); // Your application code here memcached.get('foo', (err, data) => { console.log('got', data.foo); }); ``` -------------------------------- ### Initializing and Using zipkin-instrumentation-redis Client - JavaScript Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-redis/README.md Demonstrates how to require the necessary libraries, create a Zipkin tracer with a context implementation and recorder, configure Redis connection options, wrap the standard Redis client with the zipkin-instrumentation-redis library, and then use the wrapped client to perform a traced Redis operation like 'get'. ```javascript const {Tracer} = require('zipkin'); const Redis = require('redis'); const zipkinClient = require('zipkin-instrumentation-redis'); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const redisConnectionOptions = { host: 'localhost', port: '6379' }; const redis = zipkinClient(tracer, Redis, redisConnectionOptions); // Your application code here redis.get('foo', (err, data) => { console.log('got', data.foo); }); ``` -------------------------------- ### Install zipkin-instrumentation-axiosjs Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-axiosjs/README.md Installs the zipkin-instrumentation-axiosjs library using npm. ```shell npm install zipkin-instrumentation-axiosjs --save ``` -------------------------------- ### Instrumenting request-promise with Request class (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-request-promise/README.md This example illustrates using the `Request` class provided by `zipkin-instrumentation-request-promise` for Zipkin tracing. It sets up a Zipkin tracer, instantiates the `ZipkinRequest` class, and then uses its `get` method to perform a traced HTTP GET request, logging the outcome. ```javascript const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const ZipkinRequest = require('zipkin-instrumentation-request-promise').default; const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const remoteServiceName = 'weather-api'; const request = new ZipkinRequest(tracer, remoteServiceName); request.get('http://api.weather.com') .then(function(body, response) { console.log('statusCode:', response && response.statusCode); console.log('body:', body); }) .catch(function(err){ console.log('error:', error); }); ``` -------------------------------- ### Initializing zipkin-transport-aws-sqs Logger and Tracer (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-transport-aws-sqs/README.md This snippet shows how to require the necessary modules, instantiate `AwsSqsLogger` with required and optional parameters (like queue URL, region, credentials), and then create a `BatchRecorder` and a `Tracer` using the configured logger. It requires `zipkin`, `zipkin-transport-aws-sqs`, and `noop-logger`. ```javascript const { Tracer, BatchRecorder } = require('zipkin'); const {AwsSqsLogger} = require('zipkin-transport-aws-sqs'); const noop = require('noop-logger'); let awsSqsLogger = new AwsSqsLogger({ queueUrl: "https://...", //mandatory endpointConfiguration: AWS.Endpoint, // optional region: 'eu-west-1', // optional, region string credentialProvider: AWS.CredentialProviderChain, // optional delaySeconds: 0, // optional log: noop // optional (defaults to console) }); const AwsSqsRecorder = new BatchRecorder({ logger: awsSqsLogger }); const tracer = new Tracer({ recorder, ctxImpl, // this would typically be a CLSContext or ExplicitContext localServiceName: 'service-a' // name of this application }); ``` -------------------------------- ### Install Zipkin JS via npm Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md Installs the core `zipkin` library as a project dependency using npm. ```Bash npm install zipkin --save ``` -------------------------------- ### Initialize Zipkin and Trace Request Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-request/README.md This snippet demonstrates how to initialize a Zipkin tracer, wrap the 'request' library for tracing, and make a traced HTTP GET request. It requires the 'express', 'zipkin', 'zipkin-instrumentation-request', and 'request' packages. ```javascript const express = require('express'); const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const wrapRequest = require('zipkin-instrumentation-request'); const request = require('request'); const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const remoteServiceName = 'weather-api'; const zipkinRequest = wrapRequest(request, {tracer, remoteServiceName}); zipkinRequest({ url: 'http://api.weather.com', method: 'GET', }, function(error, response, body) { console.log('error:', error); console.log('statusCode:', response && response.statusCode); console.log('body:', body); }); ``` -------------------------------- ### Setup Zipkin Tracer with Console Recorder Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md Configures a Zipkin tracer using `ExplicitContext` and `ConsoleRecorder` for debugging purposes, logging trace spans directly to the console instead of sending them over the network. ```JavaScript const tracer = new Tracer({ ctxImpl: new ExplicitContext(), recorder: new ConsoleRecorder(), localServiceName: 'service-a' // name of this application }); ``` -------------------------------- ### Combining Zipkin Middleware and Proxy Wrapping with CLS Context Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-express/README.md This example demonstrates how to use both the expressMiddleware and the wrapped express-http-proxy together. It highlights the use of zipkin-context-cls for proper context propagation across asynchronous operations, which is crucial when tracing both incoming requests and outgoing proxy calls. ```javascript const {ConsoleRecorder, Tracer} = require('zipkin'); const {expressMiddleware, wrapExpressHttpProxy} = require('zipkin-instrumentation-express') const CLSContext = require('zipkin-context-cls'); const proxy = require('express-http-proxy'); const ctxImpl = new CLSContext(); const recorder = new ConsoleRecorder(); const tracer = new Tracer({ctxImpl, localServiceName: 'weather-app', recorder}); const remoteServiceName = 'weather-api'; const zipkinProxy = wrapExpressHttpProxy(proxy, {tracer, remoteServiceName}); app.use('/api/weather', expressMiddleware({tracer}), zipkinProxy('http://api.weather.com')); ``` -------------------------------- ### Using Custom Fetch Implementation with HttpLogger (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-transport-http/README.md Illustrates how to plug in a custom fetch implementation into the `HttpLogger`. This example uses `fetch-retry` to add retry logic and exponential back-off for sending spans, improving resilience against network issues or temporary collector unavailability. ```javascript const {HttpLogger} = require('zipkin-transport-http'); const fetch = require('node-fetch'); const fetchRetryBuilder = require('fetch-retry'); const fetchRetryOptions = { // retry on any network error, or > 408 or 5xx status codes retryOn: (attempt, error, response) => error !== null || response == null || response.status >= 408, retryDelay: tryIndex => 1000 ** tryIndex // with an exponentially growing backoff }; const fetchImplementation = fetchRetryBuilder(fetch, fetchRetryOptions); const httpLogger = new HttpLogger({ endpoint: `http://localhost:9411/api/v1/spans`, httpInterval: 1, fetchImplementation }); ``` -------------------------------- ### Original JavaScript Test Snippet Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md An example JavaScript test snippet showing the original code before adding a breakpoint for debugging. ```javascript it('should handle overlapping server and client', () => { recorder.record(newRecord(rootId, new Annotation.ServiceName('frontend'))); } ``` -------------------------------- ### Wrap rest Client with Zipkin Interceptor (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-cujojs-rest/README.md This snippet shows how to initialize a Zipkin tracer and wrap the 'rest' client from 'cujojs/rest' with the provided interceptor. This adds automatic tracing to outgoing HTTP requests made using the wrapped client. Requires 'zipkin', 'rest', and 'zipkin-instrumentation-cujojs-rest' dependencies. ```javascript const {Tracer} = require('zipkin'); const rest = require('rest'); const {restInterceptor} = require('zipkin-instrumentation-cujojs-rest'); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const remoteServiceName = 'youtube'; const client = rest.wrap(restInterceptor, {tracer, remoteServiceName}); // Your application code here client('http://www.youtube.com/').then(success => { console.log('got result from YouTube'); }, error => { console.error('Error', error); }); ``` -------------------------------- ### Enable Microsecond Precision Clock in Browser Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md Installs and uses the `browser-process-hrtime` shim to provide microsecond-level clock precision in a browser environment, necessary for accurate Zipkin timestamps. ```javascript // use higher-precision time than milliseconds process.hrtime = require('browser-process-hrtime'); ``` -------------------------------- ### Instrumenting request-promise with wrapRequest (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-request-promise/README.md This snippet shows how to use the `wrapRequest` function from `zipkin-instrumentation-request-promise` to add Zipkin tracing to HTTP requests made with `request-promise`. It initializes a Zipkin tracer, wraps the `request` function, and then uses the wrapped function to make a traced GET request to a weather API, logging the response or error. ```javascript const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const {wrapRequest} = require('zipkin-instrumentation-request-promise'); const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const remoteServiceName = 'weather-api'; const request = wrapRequest(tracer, remoteServiceName); request({ url: 'http://api.weather.com', method: 'GET', }) .then(function(body, response) { console.log('statusCode:', response && response.statusCode); console.log('body:', body); }) .catch(function(err){ console.log('error:', error); }); ``` -------------------------------- ### Basic CLSContext Initialization (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-context-cls/README.md Initializes the Zipkin Tracer with the CLSContext implementation for transparent context propagation. Requires the 'zipkin-context-cls' module and a Tracer instance. ```javascript const CLSContext = require('zipkin-context-cls'); const tracer = new Tracer({ ctxImpl: new CLSContext('zipkin'), recorder, // typically HTTP or Kafka localServiceName: 'service-a' // name of this application }); ``` -------------------------------- ### Integrating Zipkin Tracing with Connect (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-connect/README.md Demonstrates how to initialize Zipkin tracing and apply the zipkin-instrumentation-connect middleware to a Connect application. Requires 'connect', 'zipkin', and 'zipkin-instrumentation-connect'. ```javascript const connect = require('connect'); const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const zipkinMiddleware = require('zipkin-instrumentation-connect'); const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const app = connect(); // Add the Zipkin middleware app.use(zipkinMiddleware({tracer})); ``` -------------------------------- ### Initializing Zipkin Tracer in Node.js Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin/README.md Demonstrates how to initialize a Zipkin Tracer instance in Node.js. It shows how to require the necessary modules, choose a context implementation (CLS or Explicit), and configure the tracer with a context, recorder, sampler, trace ID format, and local service name. ```javascript const zipkin = require('zipkin'); // In Node.js, the recommended context API to use is zipkin-context-cls. const CLSContext = require('zipkin-context-cls'); const ctxImpl = new CLSContext(); // if you want to use CLS const xtxImpl = new zipkin.ExplicitContext(); // Alternative; if you want to pass around the context manually // Tracer will be a one to many relationship with instrumentation that use it (like express) const tracer = new zipkin.Tracer({ ctxImpl, // the in-process context recorder: new zipkin.ConsoleRecorder(), // For easy debugging. You probably want to use an actual implementation, like Kafka or AWS SQS. sampler: new zipkin.sampler.CountingSampler(0.01), // sample rate 0.01 will sample 1 % of all incoming requests traceId128Bit: true, // to generate 128-bit trace IDs. 64-bit (false) is default localServiceName: 'my-service' // indicates this node in your service graph }); ``` -------------------------------- ### Integrating Zipkin Middleware with Hapi Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-hapi/README.md This snippet demonstrates how to set up a basic Hapi server and integrate the zipkin-instrumentation-hapi middleware. It shows how to require necessary modules, configure a Zipkin tracer with a console recorder, create a Hapi server instance, and register the Zipkin middleware plugin with the tracer options. ```javascript const Hapi = require('hapi'); const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const zipkinMiddleware = require('zipkin-instrumentation-hapi').hapiMiddleware; const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const server = new Hapi.Server(); // Add the Zipkin middleware server.register({ plugin: zipkinMiddleware, options: {tracer} }); ``` -------------------------------- ### CLSContext Initialization with Async/Await Support (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-context-cls/README.md Initializes the Zipkin Tracer with CLSContext, enabling experimental async/await support by using the 'cls_hooked' library which leverages Node.js async_hooks. Note that async_hooks may have performance implications. ```javascript const CLSContext = require('zipkin-context-cls'); const tracer = new Tracer({ ctxImpl: new CLSContext('zipkin', true), recorder, localServiceName: 'service-a' }); ``` -------------------------------- ### Wrap Got Client with Zipkin Instrumentation (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-gotjs/README.md This snippet shows how to import the necessary libraries, create a Zipkin tracer, wrap the Got client with the tracer, and make a traced HTTP request. ```javascript const got = require('got'); const {Tracer} = require('zipkin'); const wrapGot = require('zipkin-instrumentation-got'); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const remoteServiceName = 'youtube'; const zipkinGot = wrapGot(got, {tracer, remoteServiceName}); // Your application code here zipkinGot('http://www.youtube.com/').then(res => res.body).then(data => ...); ``` -------------------------------- ### Instrumenting pg Client and Pool with Zipkin Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-postgres/README.md This snippet shows how to wrap the standard 'pg' library's Client and Pool classes using 'zipkin-instrumentation-postgres', create instrumented instances, and execute queries using both callback and promise styles. It requires 'zipkin', 'pg', and 'zipkin-instrumentation-postgres' as dependencies. ```javascript const {Tracer} = require('zipkin'); const Postgres = require('pg'); const zipkinClient = require('zipkin-instrumentation-postgres'); const tracer = new Tracer({ctxImpl, recorder}); // configure your tracer properly here const ZipkinPostgres = zipkinClient(tracer, Postgres); const connectionOptions = { user: 'postgres', password: 'secret', host: 'localhost', database: 'mydb' }; const client = new ZipkinPostgres.Client(connectionOptions); const pool = new ZipkinPostgres.Pool(connectionOptions); // Your application code here client.query('SELECT NOW()', (err, result) => { console.log(err, result); }); pool.query('SELECT NOW()') .then(console.log) .catch(console.error); ``` -------------------------------- ### Integrating Zipkin Tracing with Express (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-connect/README.md Demonstrates how to initialize Zipkin tracing and apply the zipkin-instrumentation-connect middleware to an Express application. Requires 'express', 'zipkin', and 'zipkin-instrumentation-connect'. ```javascript const express = require('express'); const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const zipkinMiddleware = require('zipkin-instrumentation-connect'); const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const app = express(); // Add the Zipkin middleware app.use(zipkinMiddleware({tracer})); ``` -------------------------------- ### Initializing Zipkin BatchRecorder with KafkaLogger (Zookeeper) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-transport-kafka/README.md Demonstrates how to configure a Zipkin BatchRecorder to send traces to Kafka using the KafkaLogger, specifying the Zookeeper connection string via `clientOpts.connectionString`. It also shows how to configure the encoder and a custom logger. ```javascript const { Tracer, BatchRecorder, jsonEncoder: {JSON_V2} } = require('zipkin'); const {KafkaLogger} = require('zipkin-transport-kafka'); const noop = require('noop-logger'); const kafkaRecorder = new BatchRecorder({ logger: new KafkaLogger({ clientOpts: { connectionString: 'localhost:2181' }, encoder: JSON_V2, // optional (defaults to THRIFT) log: noop // optional (defaults to console) }) }); const tracer = new Tracer({ recorder, ctxImpl, // this would typically be a CLSContext or ExplicitContext localServiceName: 'service-a' // name of this application }); ``` -------------------------------- ### Configuring Zipkin Middleware for Express Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-express/README.md This snippet demonstrates how to initialize Zipkin components (Tracer, Context, Recorder) and apply the zipkinMiddleware to an Express application using app.use(). This middleware automatically traces incoming requests. ```javascript const express = require('express'); const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const zipkinMiddleware = require('zipkin-instrumentation-express').expressMiddleware; const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const app = express(); // Add the Zipkin middleware app.use(zipkinMiddleware({tracer})); ``` -------------------------------- ### Integrating Zipkin Tracing with Restify (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-connect/README.md Demonstrates how to initialize Zipkin tracing and apply the zipkin-instrumentation-connect middleware to a Restify application. Requires 'restify', 'zipkin', and 'zipkin-instrumentation-connect'. ```javascript const restify = require('restify'); const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const zipkinMiddleware = require('zipkin-instrumentation-connect'); const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const app = restify.createServer(); // Add the Zipkin middleware app.use(zipkinMiddleware({tracer})); ``` -------------------------------- ### Initializing Zipkin Middleware for Koa Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-koa/README.md This snippet demonstrates how to initialize and apply the zipkin-instrumentation-koa middleware to a Koa application. It sets up a Zipkin tracer using ConsoleRecorder and ExplicitContext, then uses the koaMiddleware function to integrate tracing into the Koa request handling pipeline. Requires 'koa', 'zipkin', and 'zipkin-instrumentation-koa'. ```javascript const Koa = require('koa'); const {Tracer, ConsoleRecorder, ExplicitContext} = require('zipkin'); const {koaMiddleware} = require('zipkin-instrumentation-koa'); const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const tracer = new Tracer({recorder, ctxImpl, localServiceName: 'zipkin-koa-demo'}); const app = new Koa(); app.use(koaMiddleware({tracer})); ``` -------------------------------- ### Initializing Zipkin BatchRecorder with KafkaLogger (Kafka Host) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-transport-kafka/README.md Shows an alternative configuration for the Zipkin BatchRecorder and KafkaLogger, using `clientOpts.kafkaHost` to specify the Kafka broker address directly, suitable when not using Zookeeper for offset management. ```javascript const {BatchRecorder} = require('zipkin'); const {KafkaLogger} = require('zipkin-transport-kafka'); const kafkaRecorder = new BatchRecorder({ logger: new KafkaLogger({ clientOpts: { kafkaHost: 'localhost:2181' } }) }); ``` -------------------------------- ### Instrumenting KafkaJS with Zipkin Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-kafkajs/README.md Demonstrates how to initialize the zipkin-instrumentation-kafkajs library, instrument a KafkaJS instance, and then use the instrumented instance to create a consumer and producer for traced single message operations. Requires a Zipkin tracer instance and Kafka version 0.11+. ```javascript const instrumentKafkaJs = require('zipkin-instrumentation-kafkajs'); const kafka = instrumentKafkaJs(new Kafka({ clientId: 'my-app', brokers: ['localhost:9092'] }), { tracer, // Your zipkin tracer instance remoteServiceName : 'kafka' // This should be the symbolic name of the broker, not a consumer. }); //Use KafkaJS as usual, single message handling will use tracing const consumer = kafka.consumer({ groupId: 'test-group' }); consumer.connect(); consumer.subscribe({ topic: 'hello' }); consumer.run({ eachMessage: async ({ topic, partition, message }) => { console.log(message.value.toString()); } }); const producer = kafka.producer(); producer.connect(); producer.send({ topic: 'topic-name', messages: [{ key: 'key1', value: 'hello world' }] }); ``` -------------------------------- ### Using Zipkin Middleware with Restify (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-restify/README.md This snippet demonstrates how to initialize a Zipkin tracer and apply the zipkin-instrumentation-restify middleware to a Restify server instance. It requires the 'restify', 'zipkin', and 'zipkin-instrumentation-restify' packages. ```javascript const restify = require('restify'); const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const zipkinMiddleware = require('zipkin-instrumentation-restify').restifyMiddleware; const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const app = restify.createServer(); // Add the Zipkin middleware app.use(zipkinMiddleware({tracer})); ``` -------------------------------- ### Wrap Fetch API with Zipkin Instrumentation - JavaScript Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-fetch/README.md Demonstrates how to use zipkin-instrumentation-fetch to wrap a standard fetch implementation with Zipkin tracing. It requires a configured Zipkin Tracer instance and a fetch function. The wrapped fetch function can then be used for making traced HTTP requests. ```javascript const {Tracer} = require('zipkin'); const wrapFetch = require('zipkin-instrumentation-fetch'); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const remoteServiceName = 'youtube'; const zipkinFetch = wrapFetch(fetch, {tracer, remoteServiceName}); // Your application code here zipkinFetch('http://www.youtube.com/').then(res => res.json()).then(data => ...); ``` -------------------------------- ### Wrap Custom Axios Instance Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-axiosjs/README.md Shows how to wrap a custom axios instance created with `axios.create()` to add Zipkin tracing support. ```javascript let axiosInstance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); axiosInstance = wrapAxios(axiosInstance, {tracer, remoteServiceName}); ``` -------------------------------- ### Integrating Zipkin Tracing with SuperAgent Request (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-superagent/README.md This snippet demonstrates how to set up a Zipkin tracer and apply the zipkin-instrumentation-superagent plugin to a SuperAgent HTTP request. It shows how to require necessary libraries, configure the tracer with context and recorder, define service names, and use the plugin with the SuperAgent .use() method to automatically trace the outgoing request. ```javascript const request = require('superagent'); const {Tracer, ExplicitContext, ConsoleRecorder} = require('zipkin'); const zipkinPlugin = require('zipkin-instrumentation-superagent'); const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const localServiceName = 'service-a'; // name of this application const tracer = new Tracer({ctxImpl, recorder, localServiceName}); const remoteServiceName = 'weather-api'; request .get('http://api.weather.com') .use(zipkinPlugin({tracer, remoteServiceName})) .end((err, res) => { // Do something }); ``` -------------------------------- ### Applying Zipkin GRPC Interceptor to Client Call in Node.js Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-grpc-client/README.md This snippet highlights the core part of using the interceptor: creating an instance of the interceptor using the `grpcInstrumentation` function with the tracer and remote service name, and then passing this interceptor instance in the options object when making a specific gRPC client method call. ```javascript const interceptor = grpcInstrumentation(grpc, {tracer, remoteServiceName}); client.getTemperature({ location: 'Tahoe'}, { interceptors: [interceptor] }, (error, response) => { console.info(`temprature in Tahoe is: ${response.temperature} `); }); ``` -------------------------------- ### Add Axios Request and Response Interceptors Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-axiosjs/README.md Illustrates how to add request and response interceptors to an axios instance, demonstrating that interceptors are supported when using zipkin-instrumentation-axiosjs. ```javascript // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Do something with response data return response; }, function (error) { // Do something with response error return Promise.reject(error); }); ``` -------------------------------- ### Run Single Test File for Specific Module using Lerna Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md Executes a specific test file (`test/batch-recorder.integrationTest.js`) within a particular module (`zipkin`) using Lerna's `--scope` option. ```bash npm run lerna-test -- --scope zipkin -- test/batch-recorder.integrationTest.js ``` -------------------------------- ### Configuring ScribeLogger and Tracer with zipkin-js Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-transport-scribe/README.md This snippet demonstrates how to configure a BatchRecorder using ScribeLogger to send trace data to a Scribe instance. It then shows how to create a Tracer instance using this recorder. Dependencies include 'zipkin', 'zipkin-transport-scribe', and 'noop-logger'. Key parameters for ScribeLogger include scribeHost, scribePort, and scribeInterval. The Tracer requires a recorder, a context implementation (ctxImpl), and a localServiceName. ```JavaScript const {Tracer, BatchRecorder} = require('zipkin'); const {ScribeLogger} = require('zipkin-transport-scribe'); const noop = require('noop-logger'); const scribeRecorder = new BatchRecorder({ logger: new ScribeLogger({ scribeHost: '127.0.0.1', scribePort: port, scribeInterval: 1, log: noop // optional (defaults to console) }) }); const tracer = new Tracer({ recorder, ctxImpl, // this would typically be a CLSContext or ExplicitContext localServiceName: 'service-a' // name of this application }); ``` -------------------------------- ### Run Tests for Specific Module using Lerna Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md Executes tests only for the specified module (`zipkin-instrumentation-postgres`) within the monorepo using Lerna's `--scope` option. ```bash npm run lerna-test -- --scope zipkin-instrumentation-postgres ``` -------------------------------- ### Run Code Style Linting Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md Executes the `yarn lint` command to check the project's code for style and formatting issues before submitting a pull request. ```bash yarn lint ``` -------------------------------- ### Tracing Promise-Returning Operations with tracer.local Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin/README.md Demonstrates using `tracer.local` to trace a function that returns a Promise. The span remains in progress until the returned Promise is resolved or rejected, ensuring the trace captures the asynchronous operation's duration. ```javascript // A span is in progress and completes when the promise is resolved. const result = tracer.local('checkout', () => { return createAPromise(); }); ``` -------------------------------- ### Wrapping express-http-proxy for Zipkin Tracing Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-instrumentation-express/README.md This code shows how to use wrapExpressHttpProxy to instrument express-http-proxy. It initializes Zipkin components and then wraps the proxy function, applying it to a specific route to trace outgoing HTTP requests made via the proxy. ```javascript const {ConsoleRecorder, Tracer, ExplicitContext} = require('zipkin'); const {wrapExpressHttpProxy} = require('zipkin-instrumentation-express'); const proxy = require('express-http-proxy'); const ctxImpl = new ExplicitContext(); const recorder = new ConsoleRecorder(); const tracer = new Tracer({ctxImpl, localServiceName: 'weather-app', recorder}); const remoteServiceName = 'weather-api'; const zipkinProxy = wrapExpressHttpProxy(proxy, {tracer, remoteServiceName}); app.use('/api/weather', zipkinProxy('http://api.weather.com', { decorateRequest: (proxyReq, originalReq) => proxyReq.method = 'POST' // You can use express-http-proxy options as usual })); ``` -------------------------------- ### Configuring HttpLogger with Custom HTTP Agent (JavaScript) Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin-transport-http/README.md Shows how to configure the `HttpLogger` with a custom Node.js `http.Agent`. This is useful for setting network-related options like using a self-signed CA, client certificates, or keeping connections alive. ```javascript // Example using a self-signed CA, along with cert/key for mTLS. new HttpLogger({ endpoint: 'http://localhost:9411/api/v2/spans', agent: new http.Agent({ ca: fs.readFileSync('pathToCaCert'), cert: fs.readFileSync('pathToCert'), key: fs.readFileSync('pathToPrivateKey') }) }) ``` -------------------------------- ### Tracing Synchronous Operations with tracer.local Source: https://github.com/openzipkin/zipkin-js/blob/master/packages/zipkin/README.md Illustrates using `tracer.local` to trace a synchronous function. A new span is created when `tracer.local` is called and automatically completes when the provided callback function finishes execution and returns a value. ```javascript // A span representing checkout completes before result is returned const result = tracer.local('checkout', () => { return someComputation(); }); ``` -------------------------------- ### Run Lerna Test Debug Command Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md Command to execute a specific test file in debug mode using the 'lerna-test-debug' script. The '--scope' flag limits execution to a specific module. ```bash npm run lerna-test-debug -- --scope zipkin -- test/batch-recorder.integrationTest.js ``` -------------------------------- ### Typescript tsconfig.json Workaround for Browser Builds Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md Provides a workaround for Typescript compilation issues in browser builds by stubbing Node.js specific modules like `node-fetch` and `os` using the `paths` option in `tsconfig.json`. ```JSON { "compilerOptions": { "baseUrl": ".", "paths": { "node-fetch": [ "node_modules/empty/index.js" ], "os": [ "node_modules/empty/index.js" ] } } } ``` -------------------------------- ### JavaScript Test Snippet with Debugger Source: https://github.com/openzipkin/zipkin-js/blob/master/README.md The same JavaScript test snippet with the 'debugger' keyword inserted. This will cause execution to pause when run in a debugger environment. ```javascript it('should handle overlapping server and client', () => { debugger recorder.record(newRecord(rootId, new Annotation.ServiceName('frontend'))); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.