在上一篇文章中,我在 Grafana Cloud 中拍攝、保存和查看了 Opentelemetry 資料
。如果您使用免費版本的 Grafana Cloud,您每月可以獲得約 50GB 的日誌和追蹤。如果是因為使用者不多,所以不會累積太多trace(或不記錄日誌)的服務,直接使用即可,但如果小規模引入的話,恐怕會累積太多日誌並爆炸。
取樣為什麼需要抽樣
上圖中的所有圓圈(軌跡)無需保存。僅儲存重要的追蹤(錯誤或太長的執行時間)和一些代表整體的樣本(一些正常的追蹤)就足夠了。
抽樣類型
頭部採樣
import { TraceIdRatioBasedSampler } from '@opentelemetry/sdk-trace-node'; const samplePercentage = 0.1; const sdk = new NodeSDK({ // Other SDK configuration parameters go here sampler: new TraceIdRatioBasedSampler(samplePercentage), });
SamplingSpanProcessor 實現
import { Context } from "@opentelemetry/api"; import { SpanProcessor, ReadableSpan, Span, } from "@opentelemetry/sdk-trace-node"; /** * Sampling span processor (including all error span and ratio of other spans) */ export class SamplingSpanProcessor implements SpanProcessor { constructor( private _spanProcessor: SpanProcessor, private _ratio: number ) {} /** * Forces to export all finished spans */ forceFlush(): Promise<void> { return this._spanProcessor.forceFlush(); } onStart(span: Span, parentContext: Context): void { this._spanProcessor.onStart(span, parentContext); } shouldSample(traceId: string): boolean { let accumulation = 0; for (let idx = 0; idx < traceId.length; idx++) { accumulation += traceId.charCodeAt(idx); } const cmp = (accumulation % 100) / 100; return cmp < this._ratio; } /** * Called when a {@link ReadableSpan} is ended, if the `span.isRecording()` * returns true. * @param span the Span that just ended. */ onEnd(span: ReadableSpan): void { // Only process spans that have an error status if (span.status.code === 2) { // Status code 0 means "UNSET", 1 means "OK", and 2 means "ERROR" this._spanProcessor.onEnd(span); } else { if (this.shouldSample(span.spanContext().traceId)) { this._spanProcessor.onEnd(span); } } } /** * Shuts down the processor. Called when SDK is shut down. This is an * opportunity for processor to do any cleanup required. */ async shutdown(): Promise<void> { return this._spanProcessor.shutdown(); } }
OtelSDK更新
spanProcessors: [ new SamplingSpanProcessor( new BatchSpanProcessor(traceExporter), samplePercentage ), ],
以上是NestJS + Opentelemetry(採樣)的詳細內容。更多資訊請關注PHP中文網其他相關文章!