Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add workflow to format using prettier #2552

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
21 changes: 21 additions & 0 deletions .github/workflows/format.yml
Original file line number Diff line number Diff line change
@@ -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
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
Loading