1. NestjsのTrace設定方法
import process from 'process';
import { TraceExporter } from '@google-cloud/opentelemetry-cloud-trace-exporter';
import {
CompositePropagator,
W3CTraceContextPropagator,
W3CBaggagePropagator,
} from '@opentelemetry/core';
import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
import { GraphQLInstrumentation } from '@opentelemetry/instrumentation-graphql';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { NestInstrumentation } from '@opentelemetry/instrumentation-nestjs-core';
import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';
import { NodeSDK } from '@opentelemetry/sdk-node';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
import {
ParentBasedSampler,
TraceIdRatioBasedSampler,
} from '@opentelemetry/sdk-trace-node';
import { ConsoleSpanExporter } from '@opentelemetry/sdk-trace-node';
const traceExporter = process.env['NODE_ENV']
? new TraceExporter()
: new ConsoleSpanExporter();
const samplePercentage = 0.1; // sample 10% of traces
export const otelSDK = new NodeSDK({
traceExporter: traceExporter,
spanProcessor: new BatchSpanProcessor(traceExporter),
textMapPropagator: new CompositePropagator({
propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()],
}),
instrumentations: [
new HttpInstrumentation(),
new ExpressInstrumentation(),
new NestInstrumentation(),
new GraphQLInstrumentation({ depth: 3, mergeItems: true }),
new PgInstrumentation({ requireParentSpan: true }),
],
sampler: new ParentBasedSampler({
root: new TraceIdRatioBasedSampler(samplePercentage),
}),
});
// gracefully shut down the SDK on process exit
process.on('SIGTERM', () => {
otelSDK
.shutdown()
.then(
() => console.log('SDK shut down successfully'),
(err) => console.log('Error shutting down SDK', err),
)
.finally(() => process.exit(0));
});
1. Cloud RunでサンプルされたリクエストだけにTraceを付与する
こちらを読むとCloud Runは自動的にTraceをサンプルしています。そのサンプルに合わせて、Traceをアプリケーション側でもつけたい事があると思います。
その場合には、sampler
に ParentBasedSampler
というのを使うことができます。
sampler: new ParentBasedSampler({
root: new TraceIdRatioBasedSampler(samplePercentage),
}),
これにより、Parentがsampledにしたがってサンプルすることができます。
This is a composite sampler. ParentBased helps distinguished between the following cases:
- No parent (root span).
- Remote parent with sampled flag true
- Remote parent with sampled flag false
- Local parent with sampled flag true
- Local parent with sampled flag false
root: new TraceIdRatioBasedSampler(samplePercentage),
これは親がなかった場合の挙動を設定するもので、ここではsamplePercentageを与えたTraceIdRatioBasedSamplerというものを設定しています。