-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
229 lines (193 loc) · 6.88 KB
/
client.ts
File metadata and controls
229 lines (193 loc) · 6.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import type {
Breadcrumb,
Client as IClient,
ClientOptions,
InternalLogEntry,
Integration,
LogLevel,
Span,
Transport,
} from '@logtide/types';
import { resolveDSN } from './dsn';
import { Scope } from './scope';
import { SpanManager, type StartSpanOptions } from './span-manager';
import { BreadcrumbBuffer } from './breadcrumb-buffer';
import { serializeError } from './utils/error-serializer';
import { generateTraceId } from './utils/trace-id';
import { LogtideHttpTransport } from './transport/logtide-http';
import { OtlpHttpTransport } from './transport/otlp-http';
import { BatchTransport } from './transport/batch';
/**
* Composite transport that sends logs via LogTide HTTP and spans via OTLP.
*/
class DefaultTransport implements Transport {
private logTransport: BatchTransport;
private spanTransport: BatchTransport;
constructor(options: ClientOptions) {
const dsn = resolveDSN(options);
this.logTransport = new BatchTransport({
inner: new LogtideHttpTransport(dsn),
batchSize: options.batchSize,
flushInterval: options.flushInterval,
maxBufferSize: options.maxBufferSize,
maxRetries: options.maxRetries,
retryDelayMs: options.retryDelayMs,
circuitBreakerThreshold: options.circuitBreakerThreshold,
circuitBreakerResetMs: options.circuitBreakerResetMs,
debug: options.debug,
});
this.spanTransport = new BatchTransport({
inner: new OtlpHttpTransport(dsn, options.service || 'unknown'),
batchSize: options.batchSize,
flushInterval: options.flushInterval,
maxBufferSize: options.maxBufferSize,
maxRetries: options.maxRetries,
retryDelayMs: options.retryDelayMs,
circuitBreakerThreshold: options.circuitBreakerThreshold,
circuitBreakerResetMs: options.circuitBreakerResetMs,
debug: options.debug,
});
}
async sendLogs(logs: InternalLogEntry[]): Promise<void> {
await this.logTransport.sendLogs(logs);
}
async sendSpans(spans: Span[]): Promise<void> {
await this.spanTransport.sendSpans(spans);
}
async flush(): Promise<void> {
await Promise.all([this.logTransport.flush(), this.spanTransport.flush()]);
}
destroy(): void {
this.logTransport.destroy();
this.spanTransport.destroy();
}
}
export class LogtideClient implements IClient {
private options: ClientOptions;
private transport: Transport & { destroy?: () => void };
private spanManager = new SpanManager();
private globalBreadcrumbs: BreadcrumbBuffer;
private integrations: Integration[] = [];
private _isInitialized = false;
constructor(options: ClientOptions) {
this.options = options;
this.globalBreadcrumbs = new BreadcrumbBuffer(options.maxBreadcrumbs ?? 100);
if (options.transport) {
this.transport = options.transport;
} else {
this.transport = new DefaultTransport(options);
}
// Install integrations
if (options.integrations) {
for (const integration of options.integrations) {
this.addIntegration(integration);
}
}
this._isInitialized = true;
}
get isInitialized(): boolean {
return this._isInitialized;
}
get service(): string | undefined {
return this.options.service;
}
get environment(): string | undefined {
return this.options.environment;
}
get release(): string | undefined {
return this.options.release;
}
private resolveService(scope?: Scope): string {
return scope?.service || this.options.service || 'unknown';
}
// ─── Logging ───────────────────────────────────────────
captureLog(
level: LogLevel | string,
message: string,
metadata?: Record<string, unknown>,
scope?: Scope,
): void {
const entry: InternalLogEntry = {
service: this.resolveService(scope),
level: level as LogLevel,
message,
time: new Date().toISOString(),
metadata: {
...metadata,
...(this.options.environment ? { environment: this.options.environment } : {}),
...(this.options.release ? { release: this.options.release } : {}),
...(scope ? { tags: scope.tags, ...scope.extras } : {}),
},
trace_id: scope?.traceId,
span_id: scope?.spanId,
breadcrumbs: scope?.getBreadcrumbs() ?? this.globalBreadcrumbs.getAll(),
};
this.transport.sendLogs([entry]);
}
captureError(
error: unknown,
metadata?: Record<string, unknown>,
scope?: Scope,
): void {
const serialized = serializeError(error);
this.captureLog(
'error',
serialized.message,
{ exception: serialized, ...metadata },
scope,
);
}
// ─── Breadcrumbs ───────────────────────────────────────
addBreadcrumb(breadcrumb: Breadcrumb): void {
this.globalBreadcrumbs.add(breadcrumb);
}
getBreadcrumbs(): Breadcrumb[] {
return this.globalBreadcrumbs.getAll();
}
// ─── Spans ─────────────────────────────────────────────
startSpan(options: StartSpanOptions): Span {
const rate = this.options.tracesSampleRate ?? 1.0;
if (Math.random() > rate) {
// Return a no-op span that won't be recorded
return {
traceId: options.traceId ?? generateTraceId(),
spanId: '0000000000000000',
name: options.name,
status: 'unset',
startTime: Date.now(),
attributes: options.attributes ?? {},
};
}
return this.spanManager.startSpan(options);
}
finishSpan(spanId: string, status: 'ok' | 'error' = 'ok'): void {
const span = this.spanManager.finishSpan(spanId, status);
if (span && this.transport.sendSpans) {
this.transport.sendSpans([span]);
}
}
// ─── Integrations ─────────────────────────────────────
addIntegration(integration: Integration): void {
integration.setup(this);
this.integrations.push(integration);
}
// ─── Scope helpers ────────────────────────────────────
createScope(traceId?: string): Scope {
return new Scope(traceId ?? generateTraceId(), this.options.maxBreadcrumbs ?? 100);
}
// ─── Lifecycle ────────────────────────────────────────
async flush(): Promise<void> {
await this.transport.flush();
}
async close(): Promise<void> {
for (const integration of this.integrations) {
integration.teardown?.();
}
this.integrations = [];
await this.flush();
if ('destroy' in this.transport && typeof this.transport.destroy === 'function') {
this.transport.destroy();
}
this._isInitialized = false;
}
}