|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const opentelemetry = require('@opentelemetry/core'); |
| 4 | +const config = require('./setup'); |
| 5 | + |
| 6 | +/** |
| 7 | + * The trace instance needs to be initialized first, if you want to enable |
| 8 | + * automatic tracing for built-in plugins (gRPC in this case). |
| 9 | + */ |
| 10 | +config.setupTracerAndExporters('grpc-client-service'); |
| 11 | + |
| 12 | +const path = require('path'); |
| 13 | +const grpc = require('grpc'); |
| 14 | +const protoLoader = require('@grpc/proto-loader'); |
| 15 | + |
| 16 | +const tracer = opentelemetry.getTracer(); |
| 17 | + |
| 18 | +const PROTO_PATH = path.join(__dirname, 'protos/defs.proto'); |
| 19 | +const PROTO_OPTIONS = { keepCase: true, enums: String, defaults: true, oneofs: true }; |
| 20 | +const definition = protoLoader.loadSync(PROTO_PATH, PROTO_OPTIONS); |
| 21 | +const rpcProto = grpc.loadPackageDefinition(definition).rpc; |
| 22 | + |
| 23 | +function main() { |
| 24 | + const client = new rpcProto.Fetch('localhost:50051', |
| 25 | + grpc.credentials.createInsecure()); |
| 26 | + const data = process.argv[2] || 'opentelemetry'; |
| 27 | + console.log('> ', data); |
| 28 | + |
| 29 | + const span = tracer.startSpan('tutorialsClient.capitalize'); |
| 30 | + tracer.withSpan(span, () => { |
| 31 | + client.capitalize({ data: Buffer.from(data) }, function (err, response) { |
| 32 | + if (err) { |
| 33 | + console.log('could not get grpc response'); |
| 34 | + return; |
| 35 | + } |
| 36 | + console.log('< ', response.data.toString('utf8')); |
| 37 | + // display traceid in the terminal |
| 38 | + console.log(`traceid: ${span.context().traceId}`); |
| 39 | + span.end(); |
| 40 | + }); |
| 41 | + }); |
| 42 | + |
| 43 | + // The process must live for at least the interval past any traces that |
| 44 | + // must be exported, or some risk being lost if they are recorded after the |
| 45 | + // last export. |
| 46 | + console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.') |
| 47 | + setTimeout(() => { console.log('Completed.'); }, 5000); |
| 48 | +} |
| 49 | + |
| 50 | +main(); |
0 commit comments