Skip to content

Commit

Permalink
chore: npm run format:fix
Browse files Browse the repository at this point in the history
  • Loading branch information
trivikr committed Nov 21, 2024
1 parent cffbf3a commit 7b901a2
Show file tree
Hide file tree
Showing 18 changed files with 284 additions and 227 deletions.
10 changes: 7 additions & 3 deletions examples/express/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

// eslint-disable-next-line import/order
import { setupTracing } from "./tracer";
import { setupTracing } from './tracer';
const tracer = setupTracing('example-express-client');

import * as api from '@opentelemetry/api';
Expand All @@ -24,8 +24,12 @@ function makeRequest() {
}
}
span.end();
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);
});
}

Expand Down
26 changes: 14 additions & 12 deletions examples/express/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { setupTracing } from './tracer'
import { setupTracing } from './tracer';

setupTracing('example-express-server');

// Require in rest of modules
import * as express from 'express';
import { default as axios } from 'axios';
import { RequestHandler } from "express";
import { RequestHandler } from 'express';

// Setup express
const app = express();
Expand All @@ -32,19 +32,21 @@ const authMiddleware: RequestHandler = (req, res, next) => {
};

app.use(express.json());
app.get('/health', (req, res) => res.status(200).send("HEALTHY")); // endpoint that is called by framework/cluster
app.get('/health', (req, res) => res.status(200).send('HEALTHY')); // endpoint that is called by framework/cluster
app.get('/run_test', async (req, res) => {
// Calls another endpoint of the same API, somewhat mimicking an external API call
const createdCat = await axios.post(`http://localhost:${PORT}/cats`, {
name: 'Tom',
friends: [
'Jerry',
],
}, {
headers: {
Authorization: 'secret_token',
const createdCat = await axios.post(
`http://localhost:${PORT}/cats`,
{
name: 'Tom',
friends: ['Jerry'],
},
});
{
headers: {
Authorization: 'secret_token',
},
}
);

return res.status(201).send(createdCat.data);
});
Expand Down
38 changes: 29 additions & 9 deletions examples/express/src/tracer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

import { SpanKind, Attributes } from "@opentelemetry/api";
import { SpanKind, Attributes } from '@opentelemetry/api';

const opentelemetry = require('@opentelemetry/api');

Expand All @@ -10,13 +10,22 @@ diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO);

import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { Sampler, AlwaysOnSampler, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import {
Sampler,
AlwaysOnSampler,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { ZipkinExporter } from '@opentelemetry/exporter-zipkin';
import { Resource } from '@opentelemetry/resources';
import { SEMRESATTRS_SERVICE_NAME, SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';
import {
SEMRESATTRS_SERVICE_NAME,
SEMATTRS_HTTP_ROUTE,
} from '@opentelemetry/semantic-conventions';

const Exporter = (process.env.EXPORTER || '').toLowerCase().startsWith('z') ? ZipkinExporter : OTLPTraceExporter;
const Exporter = (process.env.EXPORTER || '').toLowerCase().startsWith('z')
? ZipkinExporter
: OTLPTraceExporter;
import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');

Expand Down Expand Up @@ -48,7 +57,11 @@ export const setupTracing = (serviceName: string) => {
return opentelemetry.trace.getTracer(serviceName);
};

type FilterFunction = (spanName: string, spanKind: SpanKind, attributes: Attributes) => boolean;
type FilterFunction = (
spanName: string,
spanKind: SpanKind,
attributes: Attributes
) => boolean;

function filterSampler(filterFn: FilterFunction, parent: Sampler): Sampler {
return {
Expand All @@ -60,10 +73,17 @@ function filterSampler(filterFn: FilterFunction, parent: Sampler): Sampler {
},
toString() {
return `FilterSampler(${parent.toString()})`;
}
}
},
};
}

function ignoreHealthCheck(spanName: string, spanKind: SpanKind, attributes: Attributes) {
return spanKind !== opentelemetry.SpanKind.SERVER || attributes[SEMATTRS_HTTP_ROUTE] !== "/health";
function ignoreHealthCheck(
spanName: string,
spanKind: SpanKind,
attributes: Attributes
) {
return (
spanKind !== opentelemetry.SpanKind.SERVER ||
attributes[SEMATTRS_HTTP_ROUTE] !== '/health'
);
}
12 changes: 8 additions & 4 deletions examples/koa/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

import { setupTracing } from "./tracer";
import { setupTracing } from './tracer';
const tracer = setupTracing('example-koa-client');
import * as api from '@opentelemetry/api';
import { default as axios } from 'axios';
Expand All @@ -16,13 +16,17 @@ function makeRequest() {
span.setStatus({ code: api.SpanStatusCode.OK });
console.log(res.statusText);
} catch (e) {
if(e instanceof Error) {
if (e instanceof Error) {
span.setStatus({ code: api.SpanStatusCode.ERROR, message: e.message });
}
}
span.end();
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);
});
}

Expand Down
20 changes: 10 additions & 10 deletions examples/koa/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
'use strict';

import * as api from '@opentelemetry/api';
import { setupTracing } from './tracer'
import { setupTracing } from './tracer';
setupTracing('example-koa-server');

// Adding Koa router (if desired)
import * as Router from "@koa/router";
import * as Koa from "koa"

import * as Router from '@koa/router';
import * as Koa from 'koa';

// Setup koa
const app = new Koa();
const PORT = 8081;
const router = new Router();

// route definitions
router.get('/run_test', runTest)
router
.get('/run_test', runTest)
.get('/post/new', addPost)
.get('/post/:id', showNewPost);

Expand All @@ -26,15 +26,15 @@ async function setUp() {

/**
* Router functions: list, add, or show posts
*/
*/
const posts = ['post 0', 'post 1', 'post 2'];

function addPost(ctx: Koa.Context) {
const newPostId = posts.length;
posts.push(`post ${newPostId}`);
const currentSpan = api.trace.getSpan(api.context.active());
currentSpan?.addEvent('Added post');
currentSpan?.setAttribute('post.id', newPostId)
currentSpan?.setAttribute('post.id', newPostId);
ctx.body = `Added post: ${posts[posts.length - 1]}`;
ctx.redirect('/post/3');
}
Expand All @@ -45,14 +45,14 @@ async function showNewPost(ctx: Koa.Context) {
const post = posts[id];
if (!post) ctx.throw(404, 'Invalid post id');
const syntheticDelay = 500;
await new Promise((r) => setTimeout(r, syntheticDelay));
await new Promise(r => setTimeout(r, syntheticDelay));
ctx.body = post;
}

function runTest(ctx: Koa.Context) {
console.log('runTest');
const currentSpan = api.trace.getSpan(api.context.active());
if (currentSpan){
if (currentSpan) {
const { traceId } = currentSpan.spanContext();
console.log(`traceid: ${traceId}`);
console.log(`Jaeger URL: http://localhost:16686/trace/${traceId}`);
Expand All @@ -65,7 +65,7 @@ function runTest(ctx: Koa.Context) {
async function noOp(ctx: Koa.Context, next: Koa.Next) {
console.log('Sample basic koa middleware');
const syntheticDelay = 100;
await new Promise((r) => setTimeout(r, syntheticDelay));
await new Promise(r => setTimeout(r, syntheticDelay));
next();
}

Expand Down
11 changes: 4 additions & 7 deletions examples/koa/src/tracer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { JaegerExporter } from '@opentelemetry/exporter-jaeger';
import { ZipkinExporter } from '@opentelemetry/exporter-zipkin';
import { Resource } from '@opentelemetry/resources';
import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions'
import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions';

const EXPORTER = process.env.EXPORTER || '';

export const setupTracing = (serviceName: string) => {
const provider = new NodeTracerProvider({
resource: new Resource({
[SEMRESATTRS_SERVICE_NAME]: serviceName
})
[SEMRESATTRS_SERVICE_NAME]: serviceName,
}),
});

let exporter;
Expand All @@ -30,10 +30,7 @@ export const setupTracing = (serviceName: string) => {
provider.addSpanProcessor(new SimpleSpanProcessor(exporter));

registerInstrumentations({
instrumentations: [
new KoaInstrumentation(),
new HttpInstrumentation(),
],
instrumentations: [new KoaInstrumentation(), new HttpInstrumentation()],
tracerProvider: provider,
});

Expand Down
100 changes: 56 additions & 44 deletions examples/mongodb/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
'use strict';

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

const tracer = setupTracing('example-mongodb-http-client')
const tracer = setupTracing('example-mongodb-http-client');
import * as http from 'http';


/** A function which makes requests and handles response. */
function makeRequest() {
// span corresponds to outgoing requests. Here, we have manually created
Expand All @@ -19,58 +18,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();
Loading

0 comments on commit 7b901a2

Please sign in to comment.