Skip to main content

lib/logging

Logging and telemetry system for True Life.

This module provides a comprehensive logging and tracing solution that works across all runtimes (web, client, server) and exports telemetry to OpenTelemetry.

Architecture

┌──────────┐     ┌──────────┐     ┌──────────┐     ┌──────────────────┐
│ Web UI │ ──► │ Client │ ──► │ Server │ ──► │ OTEL Collector │
└──────────┘ └──────────┘ └──────────┘ └──────────────────┘


┌──────────────────┐
│ Tempo / Loki │
└──────────────────┘


┌──────────────────┐
│ Grafana │
└──────────────────┘

Quick Start

import { log, createLogger, withSpan } from "@core/logging";
 
// Simple logging
log.info("Application started");
log.error("Something failed", new Error("oops"));
 
// Module-specific logger
const logger = createLogger("banking");
logger.info("Transaction complete", { amount: 100 });
 
// Traced operations
await withSpan("process-payment", async (span) => {
    span.attributes = { orderId: "123" };
    log.info("Processing payment...");
    await processPayment();
});

Trace Context Propagation

Trace context flows from web → client → server, creating a unified trace:

[web:button-click]
└── [client:handle-interaction]
└── [server:process-request]

Enumerations

EnumerationDescription
LogLevelLog severity levels aligned with OpenTelemetry severity numbers.

Classes

ClassDescription
LoggerStructured logger with trace context support.

Interfaces

InterfaceDescription
LoggerConfigConfiguration for the logger.
LogRecordA structured log record compatible with OTLP Log Data Model.
LogSinkInterface for log sinks that process log records.
RedactionConfigConfiguration for the redaction system.
SensitivePatternConfiguration for a sensitive field pattern.
SpanA span representing a unit of work in a trace.
TelemetryBatchBatch of telemetry data for forwarding between runtimes. Used for the web → client → server pipeline.
TraceContextW3C Trace Context compatible trace context.
TraceStackStack of trace contexts for nested operations. Allows building a trace hierarchy as requests flow through the system.

Type Aliases

Type AliasDescription
AttributesArbitrary attributes that can be attached to log records and spans.
LogLevelNameString representation of log levels for human readability.
PiiTypeNameType representing valid PII type identifiers.
RedactionStrategyStrategy for redacting sensitive values.
RuntimeRuntime environment identifier.

Variables

DEFAULT_LOGGER_CONFIG

const DEFAULT_LOGGER_CONFIG: LoggerConfig;

Defined in: src/lib/logging/types.ts:291

Default logger configuration.


log

const log: Logger;

Defined in: src/lib/logging/logger.ts:458

Global logger instance. Use this for quick logging without creating a module-specific logger.


LOG_LEVEL_NAMES

const LOG_LEVEL_NAMES: Record\<LogLevel, LogLevelName\>;

Defined in: src/lib/logging/types.ts:45

Maps LogLevel enum to string names.


LOG_LEVEL_VALUES

const LOG_LEVEL_VALUES: Record\<LogLevelName, LogLevel\>;

Defined in: src/lib/logging/types.ts:57

Maps string names to LogLevel enum values.


PiiType

const PiiType: {
  BearerToken: "bearerToken";
  ConnectionString: "connectionString";
  CreditCard: "creditCard";
  Email: "email";
  IntlPhone: "intlPhone";
  Ipv4: "ipv4";
  Jwt: "jwt";
  Ssn: "ssn";
  UsPhone: "usPhone";
};

Defined in: src/lib/logging/redaction.ts:224

PII type identifiers for value-based detection. Used for type-safe PII type handling throughout the redaction system.

Type Declaration

NameTypeDefault valueDefined in
BearerToken"bearerToken""bearerToken"src/lib/logging/redaction.ts:232
ConnectionString"connectionString""connectionString"src/lib/logging/redaction.ts:233
CreditCard"creditCard""creditCard"src/lib/logging/redaction.ts:227
Email"email""email"src/lib/logging/redaction.ts:225
IntlPhone"intlPhone""intlPhone"src/lib/logging/redaction.ts:229
Ipv4"ipv4""ipv4"src/lib/logging/redaction.ts:230
Jwt"jwt""jwt"src/lib/logging/redaction.ts:231
Ssn"ssn""ssn"src/lib/logging/redaction.ts:226
UsPhone"usPhone""usPhone"src/lib/logging/redaction.ts:228

sinkRegistry

const sinkRegistry: SinkRegistry;

Defined in: src/lib/logging/sinks.ts:99

Global sink registry instance.

Functions

FunctionDescription
addSensitivePatternAdds a custom sensitive pattern.
buildTraceStackBuilds a trace stack from the current context stack.
clearContextStackClears the entire context stack. Useful for cleanup between tests or on shutdown.
clearSinksClears all registered sinks. Primarily used for testing.
createContextFromStackCreates a trace context from a trace stack received from another runtime. This continues the trace by creating a new span as a child of the last span.
createLoggerCreates a logger for a specific module.
createTraceContextCreates a new trace context, optionally as a child of an existing context.
emitToSinksEmits a log record to all registered sinks. This is called by the logging system when a log is created.
endSpanEnds a span and pops it from the context stack.
flushTelemetryManually triggers a flush of pending telemetry.
generateSpanIdGenerates a new span ID (16 hex characters).
generateTraceIdGenerates a new trace ID (32 hex characters).
getActiveSpanGets an active span by its span ID.
getCurrentContextGets the current trace context, if any.
getRedactionConfigGets the current redaction configuration.
getRuntimeGets the current runtime.
getSensitivePatternsGets all active sensitive patterns (built-in + custom + config).
initTelemetryForwarderInitializes the telemetry forwarder. Should be called once during app initialization.
isSafeValueChecks if a value is marked as safe.
onLogRecordRegisters a listener for log records. The listener will be called for every log emitted after registration.
onSpanEndRegisters a listener for when spans end.
onSpanStartRegisters a listener for when spans start.
parseTraceparentParses a W3C traceparent header into a trace context.
popContextPops the current trace context from the stack.
pushContextPushes a trace context onto the stack.
redactAttributesRedacts sensitive information from log attributes.
redactErrorCreates a safe copy of an error for logging. Redacts any PII that might be in the error message.
redactMessageRedacts a log message by detecting inline PII. This is useful for catching PII that might be embedded in log messages.
redactStringRedacts a single string value, detecting PII patterns.
registerSinkRegisters a log sink.
removeSensitivePatternRemoves a custom sensitive pattern.
resetRedactionConfigResets redaction configuration to defaults.
safeValueMarks a value as safe to log without redaction. Use this sparingly and only for values you're certain don't contain PII.
serializeTraceparentSerializes a trace context to a W3C traceparent header format.
setForwarderConfigUpdates forwarder configuration.
setForwarderEnabledEnables or disables telemetry forwarding.
setLogLevelSets the minimum log level for the global logger.
setRedactionConfigUpdates the redaction configuration.
setRuntimeSets the current runtime. Called during initialization.
shutdownTelemetryForwarderShuts down the telemetry forwarder. Flushes any pending telemetry before stopping.
startSpanStarts a new span and pushes it onto the context stack.
withSpanExecutes a function within a new span context. Automatically ends the span when the function completes.
withSpanSyncSynchronous version of withSpan for non-async operations.