Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopObservability.ts

627 lines22.5 KB

1import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
2import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
3import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
4import { retryWindowsFileSystemOperation } from "@t3tools/shared/windowsFileRetry";
5import * as Context from "effect/Context";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Logger from "effect/Logger";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as PlatformError from "effect/PlatformError";
14import * as References from "effect/References";
15import * as Ref from "effect/Ref";
16import * as Schema from "effect/Schema";
17import * as Scope from "effect/Scope";
18import * as Semaphore from "effect/Semaphore";
19import * as SynchronizedRef from "effect/SynchronizedRef";
20import * as Tracer from "effect/Tracer";
21import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
22​
23import * as DesktopEnvironment from "./DesktopEnvironment.ts";
24​
25const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
26const DESKTOP_LOG_FILE_MAX_FILES = 10;
27const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
28const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
29const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
30const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
31​
32export interface RotatingLogFileWriter {
33 readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
34 readonly writeText: (chunk: string) => Effect.Effect<void>;
36​
37export interface DesktopBackendOutputLogShape {
38 readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
39 readonly writeOutputChunk: (
40 streamName: "stdout" | "stderr",
41 chunk: Uint8Array,
42 ) => Effect.Effect<void>;
43 readonly persistFailureSnapshot: (input: { readonly details: string }) => Effect.Effect<void>;
44 readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
45 readonly discardSession: Effect.Effect<void>;
47​
48// Factory for per-instance backend output logs. `forInstance(id)` returns
49// a writer that targets a distinct rotating log file — the primary
50// instance keeps `server-child.log` so the historical path stays stable
51// for ops; other instances get `server-child-<sanitized-id>.log`.
52//
53// Writers are cached per id within a single factory instance so repeated
54// `forInstance` calls (e.g. during a backend restart that re-resolves
55// services) reuse the same rotating writer rather than racing each other
56// on the same file.
57export class DesktopBackendOutputLogFactory extends Context.Service<
58 DesktopBackendOutputLogFactory,
59 {
60 readonly forInstance: (id: string) => Effect.Effect<DesktopBackendOutputLogShape>;
61 }
62>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLogFactory") {}
63​
64const textEncoder = new TextEncoder();
65const textDecoder = new TextDecoder();
66​
67export type DesktopLogAnnotations = Record<string, unknown>;
68​
69export interface DesktopComponentLogger {
70 readonly annotate: <A, E, R>(
71 effect: Effect.Effect<A, E, R>,
72 annotations?: DesktopLogAnnotations,
73 ) => Effect.Effect<A, E, R>;
74 readonly logDebug: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
75 readonly logInfo: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
76 readonly logWarning: (
77 message: string,
78 annotations?: DesktopLogAnnotations,
79 ) => Effect.Effect<void>;
80 readonly logError: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
82​
83export function makeComponentLogger(component: string): DesktopComponentLogger {
84 const annotate: DesktopComponentLogger["annotate"] = (effect, annotations) =>
85 effect.pipe(
86 Effect.annotateLogs({
87 component,
88 ...annotations,
89 }),
90 );
91​
92 return {
93 annotate,
94 logDebug: (message, annotations) => annotate(Effect.logDebug(message), annotations),
95 logInfo: (message, annotations) => annotate(Effect.logInfo(message), annotations),
96 logWarning: (message, annotations) => annotate(Effect.logWarning(message), annotations),
97 logError: (message, annotations) => annotate(Effect.logError(message), annotations),
98 };
100​
101class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
102 "DesktopLogFileWriterConfigurationError",
103 {
104 option: Schema.Literals(["maxBytes", "maxFiles"]),
105 value: Schema.Number,
106 },
107) {
108 override get message() {
109 return `${this.option} must be >= 1 (received ${this.value})`;
110 }
112​
113type DesktopLogFileWriterError =
114 | DesktopLogFileWriterConfigurationError
115 | PlatformError.PlatformError;
116​
117const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
118​
119const DesktopBackendChildLogRecord = Schema.Struct({
120 message: Schema.String,
121 level: Schema.Literals(["INFO", "ERROR"]),
122 timestamp: Schema.String,
123 annotations: Schema.Record(Schema.String, Schema.Unknown),
124 spans: Schema.Record(Schema.String, Schema.Unknown),
125 fiberId: Schema.String,
126});
127​
128const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
129 Schema.fromJsonString(DesktopBackendChildLogRecord),
130);
131​
132const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
133 beginSession: () => Effect.void,
134 writeOutputChunk: () => Effect.void,
135 persistFailureSnapshot: () => Effect.void,
136 persistFailure: () => Effect.void,
137 discardSession: Effect.void,
138};
139​
140interface BufferedBackendOutputChunk {
141 readonly streamName: "stdout" | "stderr";
142 readonly chunk: Uint8Array;
143 readonly offset: number;
145​
146interface BackendOutputSession {
147 readonly runId: string;
148 readonly startDetails: string;
149 readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
150 readonly byteLength: number;
152​
153export function appendBoundedOutputChunk(
154 session: BackendOutputSession,
155 streamName: "stdout" | "stderr",
156 chunk: Uint8Array,
157): BackendOutputSession {
158 if (chunk.byteLength === 0) {
159 return session;
160 }
161​
162 const retainedChunk =
163 chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
164 ? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
165 : chunk.slice();
166 const chunks = [...session.chunks, { streamName, chunk: retainedChunk, offset: 0 }];
167 let byteLength = session.byteLength + retainedChunk.byteLength;
168 let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
169 let firstRetainedIndex = 0;
170​
171 while (overflow > 0) {
172 const first = chunks[firstRetainedIndex];
173 if (!first) break;
174 const retainedByteLength = first.chunk.byteLength - first.offset;
175 if (retainedByteLength <= overflow) {
176 overflow -= retainedByteLength;
177 byteLength -= retainedByteLength;
178 firstRetainedIndex += 1;
179 continue;
180 }
181​
182 chunks[firstRetainedIndex] = {
183 ...first,
184 offset: first.offset + overflow,
185 };
186 byteLength -= overflow;
187 overflow = 0;
188 }
189​
190 const excessChunks = Math.max(
191 0,
192 chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
193 );
194 for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
195 const chunk = chunks[index];
196 byteLength -= chunk ? chunk.chunk.byteLength - chunk.offset : 0;
197 }
198 firstRetainedIndex += excessChunks;
199​
200 return {
201 ...session,
202 chunks: chunks.slice(firstRetainedIndex),
203 byteLength,
204 };
206​
207const currentDesktopRunId = Effect.gen(function* () {
208 const annotations = yield* References.CurrentLogAnnotations;
209 const runId = annotations.runId;
210 return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
211});
212​
213const refreshFileSize = (
214 fileSystem: FileSystem.FileSystem,
215 filePath: string,
216): Effect.Effect<number, never> =>
217 fileSystem.stat(filePath).pipe(
218 Effect.map((stat) => Number(stat.size)),
219 Effect.orElseSucceed(() => 0),
220 );
221​
222const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
223 readonly filePath: string;
224 readonly maxBytes?: number;
225 readonly maxFiles?: number;
226}): Effect.fn.Return<
227 RotatingLogFileWriter,
228 DesktopLogFileWriterError,
229 FileSystem.FileSystem | Path.Path
230> {
231 const fileSystem = yield* FileSystem.FileSystem;
232 const path = yield* Path.Path;
233 const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
234 const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
235 const directory = path.dirname(input.filePath);
236 const baseName = path.basename(input.filePath);
237​
238 if (maxBytes < 1) {
239 return yield* new DesktopLogFileWriterConfigurationError({
240 option: "maxBytes",
241 value: maxBytes,
242 });
243 }
244 if (maxFiles < 1) {
245 return yield* new DesktopLogFileWriterConfigurationError({
246 option: "maxFiles",
247 value: maxFiles,
248 });
249 }
250​
251 yield* retryWindowsFileSystemOperation(
252 fileSystem.makeDirectory(directory, { recursive: true }),
253 );
254​
255 const withSuffix = (index: number) => `${input.filePath}.${index}`;
256 const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
257 const mutex = yield* Semaphore.make(1);
258​
259 const pruneOverflowBackups = Effect.gen(function* () {
260 const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
261 for (const entry of entries) {
262 if (!entry.startsWith(`${baseName}.`)) continue;
263 const suffix = Number(entry.slice(baseName.length + 1));
264 if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
265 yield* retryWindowsFileSystemOperation(
266 fileSystem.remove(path.join(directory, entry), { force: true }),
267 ).pipe(Effect.ignore);
268 }
269 });
270​
271 const rotate = Effect.gen(function* () {
272 yield* retryWindowsFileSystemOperation(
273 fileSystem.remove(withSuffix(maxFiles), { force: true }),
274 ).pipe(Effect.ignore);
275 for (let index = maxFiles - 1; index >= 1; index -= 1) {
276 const source = withSuffix(index);
277 const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
278 if (sourceExists) {
279 yield* retryWindowsFileSystemOperation(
280 fileSystem.rename(source, withSuffix(index + 1)),
281 );
282 }
283 }
284 const currentExists = yield* fileSystem
285 .exists(input.filePath)
286 .pipe(Effect.orElseSucceed(() => false));
287 if (currentExists) {
288 yield* retryWindowsFileSystemOperation(
289 fileSystem.rename(input.filePath, withSuffix(1)),
290 );
291 }
292 yield* Ref.set(currentSize, 0);
293 }).pipe(
294 Effect.catch(() =>
295 refreshFileSize(fileSystem, input.filePath).pipe(
296 Effect.flatMap((size) => Ref.set(currentSize, size)),
297 ),
298 ),
299 );
300​
301 const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
302 if (chunk.byteLength === 0) return Effect.void;
303​
304 return mutex.withPermits(1)(
305 Effect.gen(function* () {
306 const beforeSize = yield* Ref.get(currentSize);
307 if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
308 yield* rotate;
309 }
310​
311 yield* retryWindowsFileSystemOperation(
312 fileSystem.writeFile(input.filePath, chunk, { flag: "a" }),
313 );
314 const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
315 yield* Ref.set(currentSize, afterSize);
316​
317 if (afterSize > maxBytes) {
318 yield* rotate;
319 }
320 }).pipe(
321 Effect.catch(() =>
322 refreshFileSize(fileSystem, input.filePath).pipe(
323 Effect.flatMap((size) => Ref.set(currentSize, size)),
324 ),
325 ),
326 ),
327 );
328 };
329​
330 yield* pruneOverflowBackups;
331​
332 return {
333 writeBytes,
334 writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
335 } satisfies RotatingLogFileWriter;
336});
337​
338const readPersistedOtlpTracesUrl: Effect.Effect<
339 Option.Option<string>,
340 never,
341 FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
342> = Effect.gen(function* () {
343 const fileSystem = yield* FileSystem.FileSystem;
344 const environment = yield* DesktopEnvironment.DesktopEnvironment;
345 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
346 if (Option.isNone(raw)) {
347 return Option.none();
348 }
349​
350 const parsed = parsePersistedServerObservabilitySettings(raw.value);
351 return Option.fromNullishOr(parsed.otlpTracesUrl);
352});
353​
354const resolveOtlpTracesUrl = Effect.gen(function* () {
355 const environment = yield* DesktopEnvironment.DesktopEnvironment;
356 if (Option.isSome(environment.otlpTracesUrl)) {
357 return environment.otlpTracesUrl;
358 }
359 return yield* readPersistedOtlpTracesUrl;
360});
361​
362const writeDevelopmentConsoleOutput = (
363 streamName: "stdout" | "stderr",
364 chunk: Uint8Array,
365): Effect.Effect<void> =>
366 Effect.sync(() => {
367 const output = streamName === "stderr" ? process.stderr : process.stdout;
368 output.write(chunk);
369 }).pipe(Effect.ignore);
370​
371const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
372 function* (
373 logFile: RotatingLogFileWriter,
374 input: {
375 readonly message: string;
376 readonly level: "INFO" | "ERROR";
377 readonly annotations: Record<string, unknown>;
378 },
379 ): Effect.fn.Return<void> {
380 return yield* Effect.gen(function* () {
381 const timestamp = DateTime.formatIso(yield* DateTime.now);
382 const encoded = yield* encodeDesktopBackendChildLogRecord({
383 message: input.message,
384 level: input.level,
385 timestamp,
386 annotations: input.annotations,
387 spans: {},
388 fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
389 });
390 yield* logFile.writeText(`${encoded}\n`);
391 }).pipe(Effect.ignore({ log: true }));
392 },
393);
394​
395const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
396​
397const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
398​
399const backendLogFilePathForInstance = (
400 environment: DesktopEnvironment.DesktopEnvironment["Service"],
401 id: string,
402): string => {
403 // Primary keeps the historical "server-child.log" path so ops scripts
404 // and packaged-build log inspection still find it where it always lived.
405 if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
406 return environment.path.join(environment.logDir, "server-child.log");
407 }
408 const sanitized = sanitizeInstanceIdForFileName(id);
409 return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
410};
411​
412// Just the IO sink. Cacheable by resolved file path so two ids that
413// sanitize to the same filename share a single RotatingLogFileWriter
414// (no race on currentSize tracking). Splitting the sink off from the
415// per-call shape lets the shape annotate writes with the *caller's*
416// id rather than whatever id created the cached writer first.
417const makeBackendOutputSinkForInstance = (
418 environment: DesktopEnvironment.DesktopEnvironment["Service"],
419 id: string,
420): Effect.Effect<
421 Option.Option<RotatingLogFileWriter>,
422 never,
423 FileSystem.FileSystem | Path.Path | Scope.Scope
424> =>
425 makeRotatingLogFileWriter({
426 filePath: backendLogFilePathForInstance(environment, id),
427 }).pipe(Effect.option);
428​
429const makeBackendOutputLogShape = (
430 environment: DesktopEnvironment.DesktopEnvironment["Service"],
431 id: string,
432 sink: Option.Option<RotatingLogFileWriter>,
433): Effect.Effect<DesktopBackendOutputLogShape> =>
434 Option.match(sink, {
435 onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),
436 onSome: (logFile) =>
437 Effect.gen(function* () {
438 const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
439 const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(
440 function* (session: BackendOutputSession, details: string) {
441 yield* writeBackendChildLogRecord(logFile, {
442 message: "backend child process failure output start",
443 level: "ERROR",
444 annotations: {
445 component: "desktop-backend-child",
446 runId: session.runId,
447 instanceId: id,
448 phase: "START",
449 details: session.startDetails,
450 },
451 });
452 for (const output of session.chunks) {
453 yield* writeBackendChildLogRecord(logFile, {
454 message: "backend child process output",
455 level: output.streamName === "stderr" ? "ERROR" : "INFO",
456 annotations: {
457 component: "desktop-backend-child",
458 runId: session.runId,
459 instanceId: id,
460 stream: output.streamName,
461 text: textDecoder.decode(output.chunk.subarray(output.offset)),
462 },
463 });
464 }
465 yield* writeBackendChildLogRecord(logFile, {
466 message: "backend child process failure output end",
467 level: "ERROR",
468 annotations: {
469 component: "desktop-backend-child",
470 runId: session.runId,
471 instanceId: id,
472 phase: "END",
473 details: sanitizeLogValue(details),
474 },
475 });
476 },
477 );
478 return {
479 beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
480 details,
481 }) {
482 const runId = yield* currentDesktopRunId;
483 yield* Ref.set(
484 sessionRef,
485 Option.some({
486 runId,
487 startDetails: sanitizeLogValue(details),
488 chunks: [],
489 byteLength: 0,
490 }),
491 );
492 }),
493 writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
494 if (environment.isDevelopment) {
495 yield* writeDevelopmentConsoleOutput(streamName, chunk);
496 }
497 yield* Ref.update(
498 sessionRef,
499 Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
500 );
501 }),
502 persistFailureSnapshot: Effect.fn(
503 "desktop.observability.backendOutput.persistFailureSnapshot",
504 )(function* ({ details }) {
505 const session = yield* Ref.get(sessionRef);
506 if (Option.isSome(session)) {
507 yield* writeFailure(session.value, details);
508 }
509 }),
510 persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
511 function* ({ details }) {
512 const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
513 if (Option.isNone(session)) return;
514 yield* writeFailure(session.value, details);
515 },
516 ),
517 discardSession: Ref.set(sessionRef, Option.none()),
518 } satisfies DesktopBackendOutputLogShape;
519 }),
520 });
521​
522const backendOutputLogFactoryLayer = Layer.effect(
523 DesktopBackendOutputLogFactory,
524 Effect.gen(function* () {
525 const environment = yield* DesktopEnvironment.DesktopEnvironment;
526 const fileSystem = yield* FileSystem.FileSystem;
527 const path = yield* Path.Path;
528 const factoryScope = yield* Scope.Scope;
529 // Per-file-path cache of the IO sink only. The per-call shape
530 // wraps the sink with the caller's instance id so a cache hit on
531 // a path collision (e.g. "wsl:default" and "wsl_default" both
532 // resolve to server-child-wsl_default.log) doesn't attribute the
533 // second caller's writes to the first caller's id. Each sink pins
534 // itself to the factory's scope so all log resources tear down
535 // together at app exit. Mutex serializes concurrent first-time
536 // lookups for the same file path.
537 const cacheRef = yield* SynchronizedRef.make<
538 ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
539 >(new Map());
540​
541 const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
542 SynchronizedRef.modifyEffect(cacheRef, (cache) => {
543 const cacheKey = backendLogFilePathForInstance(environment, id);
544 const cached = cache.get(cacheKey);
545 if (cached !== undefined) {
546 return makeBackendOutputLogShape(environment, id, cached).pipe(
547 Effect.map((outputLog) => [outputLog, cache] as const),
548 );
549 }
550 return makeBackendOutputSinkForInstance(environment, id).pipe(
551 Effect.provideService(FileSystem.FileSystem, fileSystem),
552 Effect.provideService(Path.Path, path),
553 Scope.provide(factoryScope),
554 Effect.map((sink) => {
555 const next = new Map(cache);
556 next.set(cacheKey, sink);
557 return { sink, next };
558 }),
559 Effect.flatMap(({ sink, next }) =>
560 makeBackendOutputLogShape(environment, id, sink).pipe(
561 Effect.map(
562 (outputLog) =>
563 [
564 outputLog,
565 next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
566 ] as const,
567 ),
568 ),
569 ),
570 );
571 });
572​
573 return DesktopBackendOutputLogFactory.of({
574 forInstance: (id) => makeForId(id),
575 });
576 }),
577);
578​
579const desktopLoggerLayer = Layer.mergeAll(
580 Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
581 Layer.succeed(References.MinimumLogLevel, "Info"),
582);
583​
584const tracerLayer = Layer.unwrap(
585 Effect.gen(function* () {
586 const environment = yield* DesktopEnvironment.DesktopEnvironment;
587 const otlpTracesUrl = yield* resolveOtlpTracesUrl;
588 const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
589 const sink = yield* makeTraceSink({
590 filePath: tracePath,
591 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
592 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
593 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
594 });
595 const delegate = Option.isNone(otlpTracesUrl)
596 ? undefined
597 : yield* OtlpTracer.make({
598 url: otlpTracesUrl.value,
599 exportInterval: `${environment.otlpExportIntervalMs} millis`,
600 resource: {
601 serviceName: "desktop",
602 attributes: {
603 "service.runtime": "desktop",
604 "service.mode": environment.isDevelopment ? "development" : "packaged",
605 },
606 },
607 });
608 const tracer = yield* makeLocalFileTracer({
609 filePath: tracePath,
610 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
611 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
612 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
613 sink,
614 ...(delegate ? { delegate } : {}),
615 });
616​
617 return Layer.succeed(Tracer.Tracer, tracer);
618 }),
619).pipe(Layer.provide(OtlpExporter.layerFlusher), Layer.provideMerge(OtlpSerialization.layerJson));
620​
621export const layer = Layer.mergeAll(
622 backendOutputLogFactoryLayer,
623 desktopLoggerLayer,
624 tracerLayer,
625 Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
626 Layer.succeed(References.TracerTimingEnabled, true),
627);