Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions examples/mongodb/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

const baseConfig = require('../../eslint.config');

module.exports = {
...baseConfig,
env: {
node: true,
},
};
4 changes: 4 additions & 0 deletions examples/mongodb/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
"description": "Example of mongodb integration with OpenTelemetry",
"main": "index.js",
"scripts": {
"lint": "eslint . --ext=ts,js,mjs",
"lint:fix": "eslint . --ext=ts,js,mjs --fix",
"docker:start": "docker run -e MONGODB_DB=opentelemetry-tests -e MONGODB_PORT=27017 -e MONGODB_HOST=127.0.0.1 -p 27017:27017 --rm mongo",
"zipkin:server": "cross-env EXPORTER=zipkin ts-node src/server.ts",
"zipkin:client": "cross-env EXPORTER=zipkin ts-node src/client.ts",
Expand Down Expand Up @@ -35,6 +37,8 @@
"@opentelemetry/instrumentation": "^0.54.2",
"@opentelemetry/instrumentation-http": "^0.54.2",
"@opentelemetry/instrumentation-mongodb": "^0.48.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.54.2",
"@opentelemetry/resources": "^1.27.0",
"@opentelemetry/sdk-trace-node": "^1.27.0",
"@opentelemetry/sdk-trace-base": "^1.27.0",
"@opentelemetry/semantic-conventions": "^1.27.0",
Expand Down
119 changes: 73 additions & 46 deletions examples/mongodb/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
'use strict';
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as api from '@opentelemetry/api';
import { setupTracing } from './tracer';

const tracer = setupTracing('example-mongodb-http-client')
import * as api from '@opentelemetry/api';
import * as http from 'http';
// eslint-disable-next-line import/extensions
import { setupTracing } from './tracer';

const tracer = setupTracing('example-mongodb-http-client');

/** A function which makes requests and handles response. */
function makeRequest() {
Expand All @@ -19,58 +33,71 @@ function makeRequest() {

api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => {
queries += 1;
http.get({
host: 'localhost',
port: 8080,
path: '/collection/',
}, (response) => {
const body: any = [];
response.on('data', (chunk) => body.push(chunk));
response.on('end', () => {
responses += 1;
console.log(body.toString());
if (responses === queries) span.end();
});
});
http.get(
{
host: 'localhost',
port: 8080,
path: '/collection/',
},
response => {
const body: any = [];
response.on('data', chunk => body.push(chunk));
response.on('end', () => {
responses += 1;
console.log(body.toString());
if (responses === queries) span.end();
});
}
);
});
api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => {
queries += 1;
http.get({
host: 'localhost',
port: 8080,
path: '/insert/',
}, (response) => {
const body: any = [];
response.on('data', (chunk) => body.push(chunk));
response.on('end', () => {
responses += 1;
console.log(body.toString());
if (responses === queries) span.end();
});
});
http.get(
{
host: 'localhost',
port: 8080,
path: '/insert/',
},
response => {
const body: any = [];
response.on('data', chunk => body.push(chunk));
response.on('end', () => {
responses += 1;
console.log(body.toString());
if (responses === queries) span.end();
});
}
);
});
api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => {
queries += 1;
http.get({
host: 'localhost',
port: 8080,
path: '/get/',
}, (response) => {
const body: any = [];
response.on('data', (chunk) => body.push(chunk));
response.on('end', () => {
responses += 1;
console.log(body.toString());
if (responses === queries) span.end();
});
});
http.get(
{
host: 'localhost',
port: 8080,
path: '/get/',
},
response => {
const body: any = [];
response.on('data', chunk => body.push(chunk));
response.on('end', () => {
responses += 1;
console.log(body.toString());
if (responses === queries) span.end();
});
}
);
});

// The process must live for at least the interval past any traces that
// must be exported, or some risk being lost if they are recorded after the
// last export.
console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.');
setTimeout(() => { console.log('Completed.'); }, 5000);
console.log(
'Sleeping 5 seconds before shutdown to ensure all records are flushed.'
);
setTimeout(() => {
console.log('Completed.');
}, 5000);
}

makeRequest();
38 changes: 28 additions & 10 deletions examples/mongodb/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,30 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as api from '@opentelemetry/api';

import { setupTracing } from './tracer';

setupTracing('example-mongodb-server');

import { accessDB } from './utils';

import * as http from 'http';
import { IncomingMessage, ServerResponse } from 'http';
import * as mongodb from 'mongodb';
import { Collection } from 'mongodb';
// eslint-disable-next-line import/extensions
import { setupTracing } from './tracer';
// eslint-disable-next-line import/extensions
import { accessDB } from './utils';

setupTracing('example-mongodb-server');

const DB_NAME = 'mydb';
const COLLECTION_NAME = 'users';
Expand Down Expand Up @@ -41,7 +56,7 @@ function handleRequest(request: IncomingMessage, response: ServerResponse) {
const currentSpan = api.trace.getSpan(api.context.active());
if (currentSpan) {
// display traceID in the terminal
const { traceId } = currentSpan?.spanContext();
const { traceId } = currentSpan.spanContext();
console.log(`traceid: ${traceId}`);
console.log(`Jaeger URL: http://localhost:16686/trace/${traceId}`);
console.log(`Zipkin URL: http://localhost:9411/zipkin/traces/${traceId}`);
Expand Down Expand Up @@ -79,9 +94,12 @@ function handleInsertQuery(response: ServerResponse) {
.then(() => {
console.log('1 document inserted');
// find document to test context
usersCollection.findOne({}).then(res => {
console.log(JSON.stringify(res));
});
usersCollection
.findOne({})
.then(res => {
console.log(JSON.stringify(res));
})
.catch(err => console.log(err));
})
.catch(err => {
console.log('Error code:', err.code);
Expand Down
16 changes: 16 additions & 0 deletions examples/mongodb/src/tracer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as api from '@opentelemetry/api';

import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
Expand All @@ -10,6 +25,7 @@ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { MongoDBInstrumentation } from '@opentelemetry/instrumentation-mongodb';
import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';

// eslint-disable-next-line import/prefer-default-export
export const setupTracing = (serviceName: string): api.Tracer => {
const provider = new NodeTracerProvider({
resource: new Resource({
Expand Down
3 changes: 2 additions & 1 deletion examples/mongodb/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,15 @@ import * as mongodb from 'mongodb';
* @param dbName The mongodb database name.
* @param options The mongodb client config options.
*/
// eslint-disable-next-line import/prefer-default-export
export function accessDB(
url: string,
dbName: string,
options: mongodb.MongoClientOptions = {}
): Promise<mongodb.Db> {
return new Promise((resolve, reject) => {
mongodb.MongoClient.connect(url, {
serverSelectionTimeoutMS: 1000
serverSelectionTimeoutMS: 1000,
})
.then(client => {
resolve(client.db(dbName));
Expand Down