diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml new file mode 100644 index 0000000000..21b9d30ceb --- /dev/null +++ b/.github/workflows/format.yml @@ -0,0 +1,21 @@ +name: Format + +on: + push: + branches: + - main + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 18 + cache: 'npm' + - run: npm ci + - name: Format + run: | + npm run format diff --git a/examples/express/src/client.ts b/examples/express/src/client.ts index 6a39414d09..e9f464132b 100644 --- a/examples/express/src/client.ts +++ b/examples/express/src/client.ts @@ -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'; @@ -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); }); } diff --git a/examples/express/src/server.ts b/examples/express/src/server.ts index ad111a2c92..1459706e77 100644 --- a/examples/express/src/server.ts +++ b/examples/express/src/server.ts @@ -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(); @@ -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); }); diff --git a/examples/express/src/tracer.ts b/examples/express/src/tracer.ts index 4ad569644f..4b0ad2ad0c 100644 --- a/examples/express/src/tracer.ts +++ b/examples/express/src/tracer.ts @@ -1,6 +1,6 @@ 'use strict'; -import { SpanKind, Attributes } from "@opentelemetry/api"; +import { SpanKind, Attributes } from '@opentelemetry/api'; const opentelemetry = require('@opentelemetry/api'); @@ -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'); @@ -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 { @@ -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' + ); } diff --git a/examples/koa/src/client.ts b/examples/koa/src/client.ts index 40af549da4..6bd5cbc106 100644 --- a/examples/koa/src/client.ts +++ b/examples/koa/src/client.ts @@ -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'; @@ -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); }); } diff --git a/examples/koa/src/server.ts b/examples/koa/src/server.ts index f21f77e7bb..13c57bccec 100644 --- a/examples/koa/src/server.ts +++ b/examples/koa/src/server.ts @@ -1,13 +1,12 @@ '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(); @@ -15,7 +14,8 @@ 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); @@ -26,7 +26,7 @@ async function setUp() { /** * Router functions: list, add, or show posts -*/ + */ const posts = ['post 0', 'post 1', 'post 2']; function addPost(ctx: Koa.Context) { @@ -34,7 +34,7 @@ function addPost(ctx: Koa.Context) { 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'); } @@ -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}`); @@ -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(); } diff --git a/examples/koa/src/tracer.ts b/examples/koa/src/tracer.ts index d0a3321a68..dfab67cc91 100644 --- a/examples/koa/src/tracer.ts +++ b/examples/koa/src/tracer.ts @@ -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; @@ -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, }); diff --git a/examples/mongodb/src/client.ts b/examples/mongodb/src/client.ts index 556aeb248f..43337ad7f7 100644 --- a/examples/mongodb/src/client.ts +++ b/examples/mongodb/src/client.ts @@ -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 @@ -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(); diff --git a/examples/mongodb/src/server.ts b/examples/mongodb/src/server.ts index b308fdc934..4070c50508 100644 --- a/examples/mongodb/src/server.ts +++ b/examples/mongodb/src/server.ts @@ -2,17 +2,17 @@ import * as api from '@opentelemetry/api'; import { setupTracing } from './tracer'; -setupTracing('example-mongodb-server') +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"; +import { Collection } from 'mongodb'; -const DB_NAME = 'mydb' -const COLLECTION_NAME = 'users' +const DB_NAME = 'mydb'; +const COLLECTION_NAME = 'users'; const URL = `mongodb://localhost:27017/${DB_NAME}`; let db: mongodb.Db; @@ -28,7 +28,6 @@ function startServer(port: number) { throw err; }); - // Creates a server const server = http.createServer(handleRequest); // Starts the server @@ -48,8 +47,8 @@ function handleRequest(request: IncomingMessage, response: ServerResponse) { try { const body = []; - request.on('error', (err) => console.log(err)); - request.on('data', (chunk) => body.push(chunk)); + request.on('error', err => console.log(err)); + request.on('data', chunk => body.push(chunk)); request.on('end', async () => { if (request.url === '/collection/') { handleCreateCollection(response); @@ -71,7 +70,8 @@ startServer(8080); function handleInsertQuery(response: ServerResponse) { const obj = { name: 'John', age: '20' }; const usersCollection: Collection = db.collection(COLLECTION_NAME); - usersCollection.insertOne(obj) + usersCollection + .insertOne(obj) .then(() => { console.log('1 document inserted'); // find document to test context propagation using callback @@ -87,8 +87,8 @@ function handleInsertQuery(response: ServerResponse) { function handleGetQuery(response: ServerResponse) { const usersCollection: Collection = db.collection(COLLECTION_NAME); - usersCollection. - find({}) + usersCollection + .find({}) .toArray() .then(() => { console.log('1 document served'); @@ -96,7 +96,7 @@ function handleGetQuery(response: ServerResponse) { }) .catch(err => { throw err; - }) + }); } function handleCreateCollection(response: ServerResponse) { @@ -108,7 +108,7 @@ function handleCreateCollection(response: ServerResponse) { .catch(err => { console.log('Error code:', err.code); response.end(err.message); - }); + }); } function handleNotFound(response: ServerResponse) { diff --git a/examples/mongodb/src/tracer.ts b/examples/mongodb/src/tracer.ts index 4e63724503..acc2174a94 100644 --- a/examples/mongodb/src/tracer.ts +++ b/examples/mongodb/src/tracer.ts @@ -1,4 +1,4 @@ -import * as api from "@opentelemetry/api"; +import * as api from '@opentelemetry/api'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { Resource } from '@opentelemetry/resources'; @@ -10,12 +10,11 @@ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { MongoDBInstrumentation } from '@opentelemetry/instrumentation-mongodb'; import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions'; - export const setupTracing = (serviceName: string): api.Tracer => { const provider = new NodeTracerProvider({ resource: new Resource({ - [SEMRESATTRS_SERVICE_NAME]: serviceName - }) + [SEMRESATTRS_SERVICE_NAME]: serviceName, + }), }); // Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings diff --git a/examples/mongodb/src/utils.ts b/examples/mongodb/src/utils.ts index bdc9d78364..837405ba7c 100644 --- a/examples/mongodb/src/utils.ts +++ b/examples/mongodb/src/utils.ts @@ -29,7 +29,7 @@ export function accessDB( ): Promise { return new Promise((resolve, reject) => { mongodb.MongoClient.connect(url, { - serverSelectionTimeoutMS: 1000 + serverSelectionTimeoutMS: 1000, }) .then(client => { resolve(client.db(dbName)); diff --git a/examples/mysql/src/client.ts b/examples/mysql/src/client.ts index de80b7bc11..8e643abcc0 100644 --- a/examples/mysql/src/client.ts +++ b/examples/mysql/src/client.ts @@ -1,7 +1,7 @@ 'use strict'; import * as api from '@opentelemetry/api'; -import { setupTracing } from "./tracer"; +import { setupTracing } from './tracer'; const tracer = setupTracing('example-mysql-client'); import * as http from 'http'; @@ -17,90 +17,109 @@ function makeRequest() { api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => { queries += 1; - http.get({ - host: 'localhost', - port: 8080, - path: '/connection/query', - }, (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: '/connection/query', + }, + 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: '/pool/query', - }, (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: '/pool/query', + }, + 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: '/pool/query-with-2-connections', - }, (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: '/pool/query-with-2-connections', + }, + 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: '/pool/query-2-pools', - }, (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: '/pool/query-2-pools', + }, + 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: '/cluster/query', - }, (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: '/cluster/query', + }, + 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(); diff --git a/examples/mysql/src/server.ts b/examples/mysql/src/server.ts index 180224e2c7..49e11a3a09 100644 --- a/examples/mysql/src/server.ts +++ b/examples/mysql/src/server.ts @@ -1,13 +1,13 @@ 'use strict'; // eslint-disable-next-line import/order -import { setupTracing } from "./tracer"; +import { setupTracing } from './tracer'; setupTracing('example-mysql-server'); import * as api from '@opentelemetry/api'; -import * as mysql from 'mysql' +import * as mysql from 'mysql'; import * as http from 'http'; -import { MysqlError } from "mysql"; -import { PoolConnection } from "mysql"; +import { MysqlError } from 'mysql'; +import { PoolConnection } from 'mysql'; const pool = mysql.createPool({ host: 'localhost', @@ -19,7 +19,7 @@ const pool2 = mysql.createPool({ host: 'localhost', user: 'root', password: 'secret', - database: 'db_test' //this db is created by init.sql + database: 'db_test', //this db is created by init.sql }); const connection = mysql.createConnection({ @@ -48,27 +48,23 @@ function startServer(port: number | undefined) { /** A function which handles requests and send response. */ function handleRequest(request: any, response: any) { - const currentSpan = api.trace.getSpan(api.context.active()) + const currentSpan = api.trace.getSpan(api.context.active()); // display traceid in the terminal const traceId = currentSpan?.spanContext().traceId; console.log(`traceid: ${traceId}`); console.log(`Zipkin URL: http://localhost:9411/zipkin/traces/${traceId}`); try { const body = []; - request.on('error', - (err: any) => console.log(err) - ); - request.on('data', - (chunk: any) => body.push(chunk) - ); + request.on('error', (err: any) => console.log(err)); + request.on('data', (chunk: any) => body.push(chunk)); request.on('end', () => { if (request.url === '/connection/query') { handleConnectionQuery(response); } else if (request.url === '/pool/query') { handlePoolQuery(response); - } else if(request.url === '/pool/query-with-2-connections') { + } else if (request.url === '/pool/query-with-2-connections') { handlePoolwith2ConnectionsQuery(response); - } else if(request.url === '/pool/query-2-pools') { + } else if (request.url === '/pool/query-2-pools') { handle2PoolsQuery(response); } else if (request.url === '/cluster/query') { handleClusterQuery(response); @@ -143,7 +139,7 @@ function handle2PoolsQuery(response: any) { }); } -function handlePoolwith2ConnectionsQuery(response: any){ +function handlePoolwith2ConnectionsQuery(response: any) { const query = 'SELECT 1 + 1 as pool_2_connections_solution'; pool.getConnection((connErr: MysqlError, conn: PoolConnection) => { if (connErr) { @@ -172,7 +168,9 @@ function handlePoolwith2ConnectionsQuery(response: any){ console.log('Error code 2:', err.code); response.end(err.message); } else { - response.end(`${query2} 2: ${results[0].pool_2_connections_solution}`); + response.end( + `${query2} 2: ${results[0].pool_2_connections_solution}` + ); pool.end(); } }); diff --git a/examples/mysql/src/tracer.ts b/examples/mysql/src/tracer.ts index 2ded0e2567..63e21c93f7 100644 --- a/examples/mysql/src/tracer.ts +++ b/examples/mysql/src/tracer.ts @@ -13,14 +13,15 @@ import { MeterProvider, PeriodicExportingMetricReader, } from '@opentelemetry/sdk-metrics'; -const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-grpc'); +const { + OTLPMetricExporter, +} = require('@opentelemetry/exporter-metrics-otlp-grpc'); const EXPORTER = process.env.EXPORTER || ''; export const setupTracing = (serviceName: string) => { - //metrics: - const meterProvider = new MeterProvider() + const meterProvider = new MeterProvider(); const metricExporter = new OTLPMetricExporter(); const metricReader = new PeriodicExportingMetricReader({ exporter: metricExporter, @@ -32,21 +33,21 @@ export const setupTracing = (serviceName: string) => { //traces: const tracerProvider = new NodeTracerProvider({ resource: new Resource({ - [SEMRESATTRS_SERVICE_NAME]: serviceName, - }),}); + [SEMRESATTRS_SERVICE_NAME]: serviceName, + }), + }); if (EXPORTER.toLowerCase().startsWith('z')) { - tracerProvider.addSpanProcessor(new SimpleSpanProcessor(new ZipkinExporter())); + tracerProvider.addSpanProcessor( + new SimpleSpanProcessor(new ZipkinExporter()) + ); } // Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings tracerProvider.register(); registerInstrumentations({ - instrumentations: [ - new HttpInstrumentation(), - new MySQLInstrumentation(), - ], + instrumentations: [new HttpInstrumentation(), new MySQLInstrumentation()], tracerProvider: tracerProvider, meterProvider: meterProvider, }); diff --git a/examples/redis/src/client.ts b/examples/redis/src/client.ts index 4f83690393..1329c9d09c 100644 --- a/examples/redis/src/client.ts +++ b/examples/redis/src/client.ts @@ -1,6 +1,6 @@ 'use strict'; -import { setupTracing } from "./tracer"; +import { setupTracing } from './tracer'; const tracer = setupTracing('example-redis-client'); import * as api from '@opentelemetry/api'; import { default as axios } from 'axios'; @@ -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); }); } diff --git a/examples/redis/src/express-tracer-handlers.ts b/examples/redis/src/express-tracer-handlers.ts index 8caed1357b..e7466b3daf 100644 --- a/examples/redis/src/express-tracer-handlers.ts +++ b/examples/redis/src/express-tracer-handlers.ts @@ -4,9 +4,12 @@ import * as api from '@opentelemetry/api'; export function getMiddlewareTracer(tracer: api.Tracer) { return (req: any, res: any, next: any) => { - const span = tracer.startSpan(`express.middleware.tracer(${req.method} ${req.path})`, { - kind: api.SpanKind.SERVER, - }); + const span = tracer.startSpan( + `express.middleware.tracer(${req.method} ${req.path})`, + { + kind: api.SpanKind.SERVER, + } + ); // End this span before sending out the response const originalSend = res.send; @@ -22,7 +25,7 @@ export function getMiddlewareTracer(tracer: api.Tracer) { export function getErrorTracer(tracer: api.Tracer) { return (err: any, _req: any, res: any, _next: any) => { console.error('Caught error', err.message); - const span = api.trace.getSpan(api.context.active()) + const span = api.trace.getSpan(api.context.active()); if (span) { span.setStatus({ code: api.SpanStatusCode.ERROR, message: err.message }); @@ -30,4 +33,3 @@ export function getErrorTracer(tracer: api.Tracer) { res.status(500).send(err.message); }; } - diff --git a/examples/redis/src/server.ts b/examples/redis/src/server.ts index b3a5c1c936..b2adbb5838 100644 --- a/examples/redis/src/server.ts +++ b/examples/redis/src/server.ts @@ -1,6 +1,6 @@ 'use strict'; -import { setupTracing } from './tracer' +import { setupTracing } from './tracer'; const tracer = setupTracing('example-redis-server'); // Require in rest of modules @@ -32,7 +32,7 @@ async function setupRoutes() { } }); - app.get('/:cmd', (req: any , res: any) => { + app.get('/:cmd', (req: any, res: any) => { if (!req.query.args) { res.status(400).send('No args provided'); return; diff --git a/examples/redis/src/setup-redis.ts b/examples/redis/src/setup-redis.ts index 7c8984aaed..36188b11c9 100644 --- a/examples/redis/src/setup-redis.ts +++ b/examples/redis/src/setup-redis.ts @@ -1,15 +1,15 @@ 'use strict'; -import {createClient} from 'redis'; +import { createClient } from 'redis'; const client = createClient('redis://localhost:6379'); -const redisPromise = new Promise(((resolve, reject) => { +const redisPromise = new Promise((resolve, reject) => { client.once('ready', () => { resolve(client); }); - client.once('error', (error) => { + client.once('error', error => { reject(error); }); -})); +}); exports.redis = redisPromise; diff --git a/examples/redis/src/tracer.ts b/examples/redis/src/tracer.ts index de70a60418..0237e92dff 100644 --- a/examples/redis/src/tracer.ts +++ b/examples/redis/src/tracer.ts @@ -16,8 +16,9 @@ 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; if (EXPORTER.toLowerCase().startsWith('z')) { @@ -32,10 +33,7 @@ export const setupTracing = (serviceName: string) => { provider.register(); registerInstrumentations({ - instrumentations: [ - new HttpInstrumentation(), - new RedisInstrumentation(), - ], + instrumentations: [new HttpInstrumentation(), new RedisInstrumentation()], tracerProvider: provider, }); diff --git a/package.json b/package.json index 09705c8907..9d26fd4a51 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,8 @@ "test:ci:changed": "nx affected -t test --base=origin/main --head=HEAD", "test-all-versions": "nx run-many -t test-all-versions", "changelog": "lerna-changelog", + "format": "prettier --check $(git ls-files '*.ts')", + "format:fix": "prettier --write $(git ls-files '*.ts')", "lint": "nx run-many -t lint && npm run lint:readme && npm run lint:markdown", "lint:fix": "nx run-many -t lint:fix && npm run lint:markdown:fix", "lint:deps": "npx --yes knip@5.33.3 --dependencies --production --tags=-knipignore",