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
| Enumeration | Description |
|---|---|
| LogLevel | Log severity levels aligned with OpenTelemetry severity numbers. |
Classes
| Class | Description |
|---|---|
| Logger | Structured logger with trace context support. |
Interfaces
| Interface | Description |
|---|---|
| LoggerConfig | Configuration for the logger. |
| LogRecord | A structured log record compatible with OTLP Log Data Model. |
| LogSink | Interface for log sinks that process log records. |
| RedactionConfig | Configuration for the redaction system. |
| SensitivePattern | Configuration for a sensitive field pattern. |
| Span | A span representing a unit of work in a trace. |
| TelemetryBatch | Batch of telemetry data for forwarding between runtimes. Used for the web → client → server pipeline. |
| TraceContext | W3C Trace Context compatible trace context. |
| TraceStack | Stack of trace contexts for nested operations. Allows building a trace hierarchy as requests flow through the system. |
Type Aliases
| Type Alias | Description |
|---|---|
| Attributes | Arbitrary attributes that can be attached to log records and spans. |
| LogLevelName | String representation of log levels for human readability. |
| PiiTypeName | Type representing valid PII type identifiers. |
| RedactionStrategy | Strategy for redacting sensitive values. |
| Runtime | Runtime 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
| Name | Type | Default value | Defined 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
| Function | Description |
|---|---|
| addSensitivePattern | Adds a custom sensitive pattern. |
| buildTraceStack | Builds a trace stack from the current context stack. |
| clearContextStack | Clears the entire context stack. Useful for cleanup between tests or on shutdown. |
| clearSinks | Clears all registered sinks. Primarily used for testing. |
| createContextFromStack | Creates 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. |
| createLogger | Creates a logger for a specific module. |
| createTraceContext | Creates a new trace context, optionally as a child of an existing context. |
| emitToSinks | Emits a log record to all registered sinks. This is called by the logging system when a log is created. |
| endSpan | Ends a span and pops it from the context stack. |
| flushTelemetry | Manually triggers a flush of pending telemetry. |
| generateSpanId | Generates a new span ID (16 hex characters). |
| generateTraceId | Generates a new trace ID (32 hex characters). |
| getActiveSpan | Gets an active span by its span ID. |
| getCurrentContext | Gets the current trace context, if any. |
| getRedactionConfig | Gets the current redaction configuration. |
| getRuntime | Gets the current runtime. |
| getSensitivePatterns | Gets all active sensitive patterns (built-in + custom + config). |
| initTelemetryForwarder | Initializes the telemetry forwarder. Should be called once during app initialization. |
| isSafeValue | Checks if a value is marked as safe. |
| onLogRecord | Registers a listener for log records. The listener will be called for every log emitted after registration. |
| onSpanEnd | Registers a listener for when spans end. |
| onSpanStart | Registers a listener for when spans start. |
| parseTraceparent | Parses a W3C traceparent header into a trace context. |
| popContext | Pops the current trace context from the stack. |
| pushContext | Pushes a trace context onto the stack. |
| redactAttributes | Redacts sensitive information from log attributes. |
| redactError | Creates a safe copy of an error for logging. Redacts any PII that might be in the error message. |
| redactMessage | Redacts a log message by detecting inline PII. This is useful for catching PII that might be embedded in log messages. |
| redactString | Redacts a single string value, detecting PII patterns. |
| registerSink | Registers a log sink. |
| removeSensitivePattern | Removes a custom sensitive pattern. |
| resetRedactionConfig | Resets redaction configuration to defaults. |
| safeValue | Marks a value as safe to log without redaction. Use this sparingly and only for values you're certain don't contain PII. |
| serializeTraceparent | Serializes a trace context to a W3C traceparent header format. |
| setForwarderConfig | Updates forwarder configuration. |
| setForwarderEnabled | Enables or disables telemetry forwarding. |
| setLogLevel | Sets the minimum log level for the global logger. |
| setRedactionConfig | Updates the redaction configuration. |
| setRuntime | Sets the current runtime. Called during initialization. |
| shutdownTelemetryForwarder | Shuts down the telemetry forwarder. Flushes any pending telemetry before stopping. |
| startSpan | Starts a new span and pushes it onto the context stack. |
| withSpan | Executes a function within a new span context. Automatically ends the span when the function completes. |
| withSpanSync | Synchronous version of withSpan for non-async operations. |