### Wonder Logger Development Setup Source: https://github.com/jenova-marie/wonder-logger/blob/main/README.md Commands to set up the development environment for the Wonder Logger project. Includes cloning the repository, installing dependencies, running tests, and building the project. ```bash # Clone repository git clone https://github.com/jenova-marie/wonder-logger.git cd wonder-logger # Install dependencies pnpm install # Run tests pnpm test # Build pnpm build ``` -------------------------------- ### Clone and Setup Wonder Logger Repository Source: https://github.com/jenova-marie/wonder-logger/blob/main/CONTRIBUTING.md Commands to clone the Wonder Logger repository and install its dependencies locally. Ensure you have Git, Node.js, and pnpm installed. ```bash git clone https://github.com/YOUR_USERNAME/wonder-logger.git cd wonder-logger pnpm install ``` -------------------------------- ### Quick Start: Create Telemetry and Manual Span Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/TRACING.md Initializes the OpenTelemetry SDK with service name and tracing exporter configuration, then demonstrates creating a manual span for custom instrumentation. ```typescript import { createTelemetry, withSpan } from '@jenova-marie/wonder-logger' const sdk = createTelemetry({ serviceName: 'my-api', tracing: { exporter: 'otlp', endpoint: 'http://localhost:4318/v1/traces' } }) // Manual instrumentation await withSpan('process-order', async () => { // Your code here }) ``` -------------------------------- ### OpenTelemetry Configuration YAML Example Source: https://github.com/jenova-marie/wonder-logger/blob/main/src/utils/otel/README.md Example YAML configuration file for OpenTelemetry setup, demonstrating service details, tracing, metrics exporters, and instrumentation settings with environment variable interpolation. ```yaml service: name: ${SERVICE_NAME:-my-api} version: ${SERVICE_VERSION:-1.0.0} environment: ${NODE_ENV:-production} otel: enabled: true tracing: enabled: true exporter: ${OTEL_TRACE_EXPORTER:-otlp} endpoint: ${OTEL_TRACES_ENDPOINT:-http://localhost:4318/v1/traces} sampleRate: 1.0 metrics: enabled: true exporters: - type: prometheus port: ${PROMETHEUS_PORT:-9464} - type: otlp endpoint: ${OTEL_METRICS_ENDPOINT:-http://localhost:4318/v1/metrics} exportIntervalMillis: 60000 instrumentation: auto: true http: true ``` -------------------------------- ### Create Logger Instance Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/LOGGING.md Initializes a Pino-based logger instance with a specified name and logging level. Ensure the '@jenova-marie/wonder-logger' package is installed. The logger can then be used to log messages with structured data. ```typescript import { createLogger } from '@jenova-marie/wonder-logger' const logger = createLogger({ name: 'my-api', level: 'info' }) logger.info({ userId: 123 }, 'User logged in') ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/media/README-2.md An example of a `wonder-logger.yaml` file demonstrating basic service, logger, and OpenTelemetry settings. This includes service metadata, logger transports, and OpenTelemetry exporter configurations. ```yaml service: name: my-api version: 1.0.0 environment: development logger: enabled: true level: info transports: - type: console pretty: true otel: enabled: true tracing: enabled: true exporter: console ``` -------------------------------- ### Quick Start: Initialize Telemetry SDK with Metrics Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/METRICS.md Initializes the wonder-logger telemetry SDK with metrics enabled, configuring a Prometheus exporter on a specific port. This sets up the basic structure for collecting and exporting metrics. ```typescript import { createTelemetry } from '@jenova-marie/wonder-logger' import { metrics } from '@opentelemetry/api' const sdk = createTelemetry({ serviceName: 'my-api', metrics: { enabled: true, exporters: [ { type: 'prometheus', port: 9464 } ] } }) // Create custom metrics const meter = metrics.getMeter('my-api') const requestCounter = meter.createCounter('http_requests_total') requestCounter.add(1, { method: 'GET', path: '/users' }) ``` -------------------------------- ### Clone Wonder Logger Repository and Install Dependencies Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/index.html Provides commands to set up the development environment for Wonder Logger. This includes cloning the repository from GitHub, navigating into the project directory, installing all necessary dependencies using pnpm, and running the initial test suite and build process. ```bash git clone https://github.com/jenova-marie/wonder-logger.git cd wonder-logger pnpm install pnpm test pnpm build ``` -------------------------------- ### Development Setup Configuration (YAML) Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/media/README-2.md An example YAML configuration file for a development environment. It includes settings for service information, logger level and transports (console with pretty printing), and OpenTelemetry with console exporter for tracing. ```yaml # wonder-logger.yaml service: name: ${SERVICE_NAME:-my-api} version: ${npm_package_version:-1.0.0} environment: development logger: enabled: true level: debug transports: - type: console pretty: true prettyOptions: colorize: true translateTime: 'HH:MM:ss' singleLine: false otel: enabled: true tracing: enabled: true exporter: console metrics: enabled: true exporters: - type: prometheus port: 9464 ``` -------------------------------- ### YAML Configuration Example for Wonder Logger Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/index.html Provides an example of a `wonder-logger.yaml` configuration file. This file defines service name, logger level, transports (console and memory), and OpenTelemetry settings, demonstrating environment variable interpolation for dynamic configuration. ```yaml # wonder-logger.yaml service: name: ${SERVICE_NAME:-my-api} logger: level: ${LOG_LEVEL:-info} transports: - type: console pretty: false - type: memory name: ${SERVICE_NAME} maxSize: 10000 # Example of setting environment variables: # export SERVICE_NAME=my-awesome-service # export LOG_LEVEL=debug # export OTEL_ENDPOINT=http://localhost:4318 ``` -------------------------------- ### Express API Logging Setup with Morgan and OpenTelemetry in TypeScript Source: https://github.com/jenova-marie/wonder-logger/blob/main/src/utils/logger/README.md Example of setting up an Express.js application with combined HTTP request logging using Morgan and sending logs to a centralized system via OpenTelemetry. Includes request-scoped logging. ```typescript import express from 'express' import morgan from 'morgan' import { createLogger, createOtelTransport, withTraceContext, createMorganStream } from './utils/logger' import { createTelemetry } from './utils/otel' // Initialize telemetry createTelemetry({ serviceName: 'api' }) // Create logger const baseLogger = createLogger({ name: 'api', transports: [ createOtelTransport({ serviceName: 'api' }) ] }) const logger = withTraceContext(baseLogger) const app = express() // HTTP request logging app.use(morgan('combined', { stream: createMorganStream(logger) })) // Request-scoped logging app.use((req, res, next) => { req.logger = logger.child({ requestId: req.headers['x-request-id'] }) next() }) app.get('/users/:id', async (req, res) => { req.logger.info({ userId: req.params.id }, 'Fetching user') const user = await db.users.findById(req.params.id) res.json(user) }) app.listen(3000, () => { logger.info({ port: 3000 }, 'Server started') }) ``` -------------------------------- ### Wonder Logger: YAML Configuration Example Source: https://github.com/jenova-marie/wonder-logger/blob/main/README.md Shows an example of a YAML configuration file for Wonder Logger. This demonstrates how to configure service name, logging level, transports (console, memory), and OpenTelemetry settings using environment variable interpolation. ```yaml # wonder-logger.yaml service: name: ${SERVICE_NAME:-my-api} logger: level: ${LOG_LEVEL:-info} transports: - type: console pretty: false - type: memory name: ${SERVICE_NAME} maxSize: 10000 otel: enabled: true tracing: exporter: otlp endpoint: ${OTEL_ENDPOINT} ``` -------------------------------- ### Production Setup Configuration (YAML) Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/media/README-2.md An example YAML configuration for a production environment. It utilizes environment variables for dynamic settings like service name, version, and log level. It configures console and OTLP transports for logging, and OTLP for tracing and metrics. ```yaml # wonder-logger.yaml service: name: ${SERVICE_NAME} version: ${SERVICE_VERSION} environment: ${NODE_ENV:-production} logger: enabled: true level: ${LOG_LEVEL:-info} redact: - password - token - apiKey - secret - creditCard transports: - type: console pretty: false - type: otel endpoint: ${OTEL_LOGS_ENDPOINT} exportIntervalMillis: 5000 plugins: traceContext: true otel: enabled: true tracing: enabled: true exporter: otlp endpoint: ${OTEL_TRACES_ENDPOINT} sampleRate: ${TRACE_SAMPLE_RATE:-0.1} metrics: enabled: true exporters: - type: otlp endpoint: ${OTEL_METRICS_ENDPOINT} exportIntervalMillis: 60000 instrumentation: auto: true http: true ``` -------------------------------- ### Install Wonder Logger using npm, yarn, or pnpm Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/index.html Instructions for installing the wonder-logger package using common Node.js package managers. This is the first step to integrating Wonder Logger into your project. ```bash npm install wonder-logger ``` ```bash yarn add wonder-logger ``` ```bash pnpm add wonder-logger ``` -------------------------------- ### Load Configuration Example Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/functions/loadConfig.html Demonstrates how to load configuration for wonder-logger, either from a default location or a custom path. It also shows how to handle optional configuration files. ```javascript // Load from default location (wonder-logger.yaml in cwd) const config = loadConfig() // Load from custom path const config = loadConfig({ configPath: './config/custom.yaml' }) // Optional config (returns null if not found) const config = loadConfig({ required: false }) ``` -------------------------------- ### OpenTelemetry SDK Wrapper Usage Example Source: https://github.com/jenova-marie/wonder-logger/blob/main/CLAUDE.md Illustrates how to use the `createTelemetry` factory function and the returned SDK wrapper object in TypeScript. It shows the instantiation of the wrapper with service name and demonstrates the usage of `forceFlush` and `shutdown` methods, while noting that `start` is automatic and core OpenTelemetry tracers/meters are accessed globally. ```typescript // Returns wrapper with helper methods const sdk = createTelemetry({ serviceName: 'my-api' }) // SDK methods await sdk.forceFlush() // Force immediate export (testing) await sdk.shutdown() // Graceful shutdown sdk.start() // Already called automatically // Tracer/Meter accessed via @opentelemetry/api globals import { trace, metrics } from '@opentelemetry/api' const tracer = trace.getTracer('my-tracer') const meter = metrics.getMeter('my-meter') ``` -------------------------------- ### Integration Test Setup File Source: https://github.com/jenova-marie/wonder-logger/blob/main/tests/integration/README.md Setup script for integration tests. This file ensures that necessary directories, such as the logs directory, are created before tests are executed, preventing potential errors related to missing file paths. ```typescript // tests/integration/setup.ts import fs from 'fs' import path from 'path' const logsDir = path.resolve(__dirname, './logs') if (!fs.existsSync(logsDir)) { fs.mkdirSync(logsDir) } // Export something if needed, or just perform setup actions export default {} ``` -------------------------------- ### OpenTelemetry Configuration YAML Example Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/media/README-1.md An example YAML file demonstrating how to configure OpenTelemetry settings for a service. It covers service details, tracing, metrics, and instrumentation options. Environment variables can be used for dynamic values, and the configuration supports multiple exporters and intervals. ```yaml service: name: ${SERVICE_NAME:-my-api} version: ${SERVICE_VERSION:-1.0.0} environment: ${NODE_ENV:-production} otel: enabled: true tracing: enabled: true exporter: ${OTEL_TRACE_EXPORTER:-otlp} endpoint: ${OTEL_TRACES_ENDPOINT:-http://localhost:4318/v1/traces} sampleRate: 1.0 metrics: enabled: true exporters: - type: prometheus port: ${PROMETHEUS_PORT:-9464} - type: otlp endpoint: ${OTEL_METRICS_ENDPOINT:-http://localhost:4318/v1/metrics} exportIntervalMillis: 60000 instrumentation: auto: true http: true ``` -------------------------------- ### Manual Span Instrumentation Example Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/index.html Example showing how to manually instrument code with spans for tracing specific operations. ```APIDOC ## Manual Span Instrumentation Example This example demonstrates how to use the `withSpan` function to manually instrument a function and record custom metrics. ```javascript import { withSpan } from 'wonder-logger' import { metrics } from '@opentelemetry/api' async function processPayment(orderId: string) { // Create a span for the 'process-payment' operation return withSpan('process-payment', async () => { // Your business logic here // Example: const charge = await stripe.charges.create(...) // Record custom metrics using OpenTelemetry API const meter = metrics.getMeter('payments') const counter = meter.createCounter('payments_processed') counter.add(1, { status: 'success' }) // Increment counter with attributes // return charge // Return the result of the operation return { success: true, orderId: orderId } }) } ``` ``` -------------------------------- ### Express Integration Example Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/index.html Example demonstrating how to integrate Wonder Logger with an Express application for request logging and request-scoped logging. ```APIDOC ## Express Integration Example This example shows how to use `wonder-logger` with Express for request logging using `morgan` and for creating request-scoped loggers. ```javascript import express from 'express' import morgan from 'morgan' import { createLogger, createTelemetry, withTraceContext, createMorganStream, withSpan } from 'wonder-logger' // Initialize telemetry first createTelemetry({ serviceName: 'my-api' }) // Create trace-aware logger const logger = withTraceContext(createLogger({ name: 'my-api' })) const app = express() // HTTP request logging using morgan and wonder-logger stream app.use(morgan('combined', { stream: createMorganStream(logger) })) // Request-scoped logging middleware app.use((req, res, next) => { // Assign a logger with a requestId to each request object req.logger = logger.child({ requestId: req.headers['x-request-id'] }) next() }) // Example route using request logger and manual span app.get('/users/:id', async (req, res) => { const user = await withSpan('fetch-user', async () => { // Use the request-scoped logger req.logger.info({ userId: req.params.id }, 'Fetching user') // Assume db.users.findById is an async function that fetches user data return await db.users.findById(req.params.id) }) res.json(user} }) // Start the server app.listen(3000, () => { logger.info({ port: 3000 }, 'Server started') }) ``` ``` -------------------------------- ### Start Telemetry SDK Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/interfaces/TelemetrySDK.html Initializes and starts the TelemetrySDK. This method is synchronous and does not return any value. ```typescript start: () => void ``` -------------------------------- ### Query Loki API Example (TypeScript) Source: https://github.com/jenova-marie/wonder-logger/blob/main/tests/e2e/README.md Example TypeScript function to query logs from Loki using its API. It demonstrates how to construct the query parameters and handle the response. ```typescript // Query Loki const logs = await queryLoki( 'https://loki.rso', '{job="app"}', startNano, endNano ) ``` -------------------------------- ### LogQL Example Query for Loki Source: https://github.com/jenova-marie/wonder-logger/blob/main/tests/e2e/README.md An example LogQL query to retrieve logs from Loki. This query filters logs based on a specific service name and content, useful for validating log ingestion. ```logql {service_name="e2e-loki-test"} |= "test-123abc" ``` -------------------------------- ### Query Tempo API Example (TypeScript) Source: https://github.com/jenova-marie/wonder-logger/blob/main/tests/e2e/README.md Example TypeScript function to query traces from Tempo using its API. It shows how to retrieve trace data by trace ID. ```typescript // Query Tempo const trace = await queryTempoTrace( 'https://tempo.rso', traceId ) ``` -------------------------------- ### E2E Test Setup and Execution for recoverysky-server Source: https://github.com/jenova-marie/wonder-logger/blob/main/CLAUDE.md Details the setup and execution commands for End-to-End (E2E) tests in the recoverysky-server project. It highlights the necessity of setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable for self-signed certificates and provides commands to run all E2E tests or specific backend tests (Loki, Tempo, Metrics). ```bash # Must set TLS env var for self-signed certs export NODE_TLS_REJECT_UNAUTHORIZED=0 # Run E2E tests pnpm test:e2e # Specific backend pnpm test tests/e2e/loki.test.ts pnpm test tests/e2e/tempo.test.ts pnpm test tests/e2e/metrics.test.ts ``` -------------------------------- ### Debugging Proxy Requests Source: https://github.com/jenova-marie/wonder-logger/blob/main/tests/e2e/DEBUG.md Guides and commands for verifying if the Caddy proxy is correctly routing requests and if DNS resolution is functioning as expected. -------------------------------- ### Configure Wonder Logger using YAML Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/index.html Example configuration file (`wonder-logger.yaml`) demonstrating how to set up service details, logging levels, transports (console, file, memory, OTel), plugins, tracing, metrics, and instrumentation. ```yaml service: name: ${SERVICE_NAME:-my-api} version: ${SERVICE_VERSION:-1.0.0} environment: ${NODE_ENV:-development} logger: enabled: true level: ${LOG_LEVEL:-info} redact: - password - token transports: # Console transport (JSON format in production) - type: console pretty: ${LOG_PRETTY:-false} # File transport (relative paths resolve from config file location) - type: file dir: ./logs fileName: app.log # Memory transport (for testing and runtime log inspection) - type: memory name: ${SERVICE_NAME:-my-api} maxSize: 10000 level: debug # OpenTelemetry transport (send to Loki, etc.) - type: otel endpoint: ${OTEL_LOGS_ENDPOINT:-http://localhost:4318/v1/logs} plugins: # Inject trace_id and span_id into logs traceContext: true otel: enabled: true tracing: enabled: true exporter: ${OTEL_TRACE_EXPORTER:-otlp} endpoint: ${OTEL_TRACES_ENDPOINT:-http://localhost:4318/v1/traces} sampleRate: 1.0 metrics: enabled: true exporters: - type: prometheus port: ${PROMETHEUS_PORT:-9464} - type: otlp endpoint: ${OTEL_METRICS_ENDPOINT:-http://localhost:4318/v1/metrics} exportIntervalMillis: 60000 instrumentation: auto: true http: true ``` -------------------------------- ### Create Custom Histogram Metric Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/METRICS.md Illustrates the creation and usage of a histogram metric to record durations. It captures the start time of an operation, performs the operation, and then records the duration with relevant labels. ```typescript const meter = metrics.getMeter('my-api') const requestDuration = meter.createHistogram('http_request_duration_ms', { description: 'HTTP request duration in milliseconds' }) const start = Date.now() // ... handle request ... const duration = Date.now() - start requestDuration.record(duration, { method: 'GET', path: '/users' }) ``` -------------------------------- ### Local Development Server for API Docs (Bash) Source: https://github.com/jenova-marie/wonder-logger/blob/main/DOCUMENTATION.md Instructions for starting a local HTTP server to view the generated TypeDoc HTML API documentation. This is useful for browsing the full API reference locally. ```bash cd node_modules/@jenova-marie/wonder-logger/docs npx http-server -p 8080 # Open http://localhost:8080 in your browser ``` -------------------------------- ### Error Handling with ts-rust-result 2.0 - Quick Start Source: https://github.com/jenova-marie/wonder-logger/blob/main/PLAN.md This code snippet provides a quick start example for using the wonder-logger library with Result-based error handling. It demonstrates how to create a logger instance and handle potential errors during its creation by checking the 'ok' property of the returned Result. If an error occurs, it's logged using 'toLogContext' and the process exits. ```typescript import { createLogger, toLogContext } from 'wonder-logger' const result = createLogger({ name: 'api' }) if (!result.ok) { // Error handling with observability console.error(toLogContext(result.error)) process.exit(1) } const logger = result.value logger.info('Logger created successfully') ``` -------------------------------- ### Add Labels to Metrics Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/METRICS.md Demonstrates how to add multi-dimensional labels (tags) to metrics, enabling more granular filtering and analysis. This example shows adding labels like method, path, status, environment, and region to a counter. ```typescript requestCounter.add(1, { method: 'GET', path: '/users', status: '200', environment: 'production', region: 'us-east-1' }) ``` ```promql # Total requests http_requests_total # Filtered by labels http_requests_total{method="GET", status="200"} # Rate of errors rate(http_requests_total{status=~"5.."}[5m]) ``` -------------------------------- ### Migration from console.log Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/media/README.md Illustrates how to transition from using `console.log` to the structured logging provided by Wonder Logger. ```APIDOC ## MIGRATION FROM CONSOLE.LOG ### Description Guidance on updating existing `console.log` statements to use the Wonder Logger API for better structure and capabilities. ### Method N/A (illustrative examples) ### Endpoint N/A ### Parameters None ### Request Example ```typescript // Old way: // console.log('User logged in:', userId); // console.error('Error:', err); // New way with Wonder Logger: import { createLogger } from '@wonder-logger/core'; const logger = createLogger(); logger.info({ userId }, 'User logged in'); logger.error({ err }, 'Error occurred'); ``` ### Response N/A (illustrative examples) ``` -------------------------------- ### Migration Example: Console.log to Wonder Logger Source: https://github.com/jenova-marie/wonder-logger/blob/main/src/utils/logger/README.md Demonstrates the transition from using `console.log` and `console.error` to the structured logging methods provided by Wonder Logger (`logger.info` and `logger.error`). Shows how to pass context data. ```typescript // Old console.log('User logged in:', userId) console.error('Error:', err) // New logger.info({ userId }, 'User logged in') logger.error({ err }, 'Error occurred') ``` -------------------------------- ### Production Best Practices for Wonder Logger Source: https://github.com/jenova-marie/wonder-logger/blob/main/README.md Outlines key recommendations for deploying Wonder Logger in a production environment. Covers using JSON logging, setting appropriate log levels, leveraging OTLP for centralized collection, and including trace context for correlation. ```typescript createConsoleTransport({ pretty: false }) level: process.env.NODE_ENV === 'production' ? 'info' : 'debug' createOtelTransport({ serviceName: 'my-api' }) const logger = withTraceContext(baseLogger) logger.info({ userId, orderId }, 'Order placed') // Good logger.info(`Order ${orderId} by ${userId}`) // Bad const requestLogger = logger.child({ requestId }) createTelemetry({ tracing: { sampleRate: 0.1 } // 10% sampling }) ``` -------------------------------- ### Mocking File System for Config Tests in TypeScript Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/TESTING.md Shows how to mock the file system using `memfs` and `vi.mock` for testing configuration loading with Wonder Logger in TypeScript. It demonstrates creating a virtual file system with a YAML configuration file and then loading it using `loadConfig` from `@jenova-marie/wonder-logger`. The test verifies that the configuration is loaded successfully. ```typescript import { vol } from 'memfs' import { loadConfig } from '@jenova-marie/wonder-logger' vi.mock('fs/promises', () => memfs.promises) it('should load config from file', () => { vol.fromJSON({ '/app/wonder-logger.yaml': ` service: name: test-service logger: level: debug ` }) const result = loadConfig({ configPath: '/app/wonder-logger.yaml' }) expect(result.ok).toBe(true) }) ``` -------------------------------- ### Theme Initialization - JavaScript Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/functions/createLoggerFromConfig.html Initializes the application theme by reading from local storage or defaulting to 'os'. It then hides the body content for a short duration to allow for theme application before showing the page. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Example Conventional Commit Message Source: https://github.com/jenova-marie/wonder-logger/blob/main/CONTRIBUTING.md An example of a detailed commit message following Conventional Commits guidelines. It includes a type, scope (optional), description, and a body explaining the changes. ```text feat: add Prometheus push gateway support - Implement push gateway exporter - Add configuration options - Update documentation ``` -------------------------------- ### createTelemetry - Basic Usage Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/media/README-1.md Initializes the OpenTelemetry SDK with minimal configuration, applying sensible defaults for tracing, metrics, and auto-instrumentation. ```APIDOC ## createTelemetry API ### Description Initializes the OpenTelemetry SDK with a service name and applies default configurations for tracing, metrics, and auto-instrumentation. ### Method Factory function (conceptual) ### Endpoint N/A (This is a library function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ##### `TelemetryOptions` Object - **serviceName** (string) - Required - The name of the service. - **serviceVersion** (string) - Optional - The version of the service. - **environment** (string) - Optional - The environment the service is running in (e.g., 'development', 'production'). Defaults to `NODE_ENV` or 'development'. - **tracing** (TracingOptions) - Optional - Configuration for tracing. - **metrics** (MetricsOptions) - Optional - Configuration for metrics. ### Request Example ```typescript import { createTelemetry } from './utils/otel' const sdk = createTelemetry({ serviceName: 'my-api', }) ``` ### Response #### Success Response (200) Returns an initialized OpenTelemetry SDK instance. #### Response Example (Conceptual: SDK instance) ```json { "sdk": "OpenTelemetry SDK Instance" } ``` ``` -------------------------------- ### Example Usage of Wonder Logger and Telemetry Initialization Source: https://github.com/jenova-marie/wonder-logger/blob/main/PLAN.md This example demonstrates the usage of the wonder-logger and telemetry initialization functions. It shows how to handle potential errors during initialization using the Result type, log errors in a structured format, and capture exceptions using Sentry. It also includes an example of how to record metrics and add error attributes to spans for distributed tracing. ```typescript import { createLogger, createTelemetry, toLogContext, toSpanAttributes, toMetricLabels } from '@jenova-marie/wonder-logger' import * as Sentry from '@sentry/node' import pino from 'pino' // Create logger const loggerResult = createLogger({ name: 'api' }) if (!loggerResult.ok) { console.error(toLogContext(loggerResult.error)) Sentry.captureException(toSentryError(loggerResult.error)) process.exit(1) } const logger = loggerResult.value // Create telemetry const sdkResult = createTelemetry({ serviceName: 'api' }) if (!sdkResult.ok) { logger.error(toLogContext(sdkResult.error), 'Failed to initialize telemetry') // Record metric errorCounter.inc(toMetricLabels(sdkResult.error)) // Add to span if in traced context const span = trace.getActiveSpan() if (span) { span.setAttributes(toSpanAttributes(sdkResult.error)) } } ``` -------------------------------- ### Wonder Logger: Logging Examples Source: https://github.com/jenova-marie/wonder-logger/blob/main/README.md Provides practical examples of using the Wonder Logger for different logging scenarios, including logging only data, only a message, both data and message, and data with message interpolation, as well as error logging. ```typescript // Data object only (no message) logger.info({ userId: 123, action: 'login' }); // Message only (no data) logger.info('Server started'); // Data object + message (most common) logger.info({ userId: 123 }, 'User logged in'); // Data object + message + interpolation const username = 'Alice'; const timestamp = new Date().toISOString(); logger.info({ userId: 123 }, 'User %s logged in at %s', username, timestamp); // Error logging (err is serialized automatically by Pino) try { await riskyOperation(); } catch (err) { logger.error({ err, userId: 123 }, 'Operation failed'); } ``` -------------------------------- ### Wonder Logger: Programmatic Configuration Loading Source: https://github.com/jenova-marie/wonder-logger/blob/main/README.md Demonstrates how to programmatically create a logger and telemetry instance from a configuration using Wonder Logger's `createLoggerFromConfig` and `createTelemetryFromConfig` functions. ```typescript import { createLoggerFromConfig, createTelemetryFromConfig } from 'wonder-logger'; const sdk = createTelemetryFromConfig(); const logger = createLoggerFromConfig(); ``` -------------------------------- ### Load Wonder Logger Configuration Programmatically Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/index.html JavaScript code demonstrating how to initialize Wonder Logger and its telemetry features by loading configuration from `wonder-logger.yaml`. This allows for observable logging and tracing in the application. ```javascript import { createLoggerFromConfig, createTelemetryFromConfig } from 'wonder-logger' // Load from wonder-logger.yaml in project root const sdk = createTelemetryFromConfig() const logger = createLoggerFromConfig() // Now start logging with full observability logger.info('Application started') logger.info({ userId: 123 }, 'User logged in') ``` -------------------------------- ### Wait for Condition Utility Example (TypeScript) Source: https://github.com/jenova-marie/wonder-logger/blob/main/tests/e2e/README.md Example of a utility function in TypeScript to wait for a specific condition to be met, with configurable retries and delay. Useful for asynchronous operations like data ingestion. ```typescript // Wait for condition with retries await waitForCondition(async () => { const result = await queryLoki(...) return result.data.result.length > 0 }, 10, 1000) ``` -------------------------------- ### Creating Logger from Configuration Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/CONFIGURATION.md Shows how to instantiate a logger instance directly from the configuration using the `createLoggerFromConfig` function. It supports loading from the default location, a custom path, or applying runtime overrides. ```typescript import { createLoggerFromConfig } from '@jenova-marie/wonder-logger' // Load from default location const logger = createLoggerFromConfig() // Custom config path const logger = createLoggerFromConfig({ configPath: './config/production.yaml' }) // With overrides const logger = createLoggerFromConfig({ overrides: { level: 'debug' // Override config file } }) logger.info('Logger ready') ``` -------------------------------- ### Create Telemetry SDK Wrapper Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/media/README-1.md Initializes the TelemetrySDK, returning a wrapper around NodeSDK with helper methods for managing telemetry. It automatically starts the SDK. Dependencies include the core OpenTelemetry SDK. ```typescript import { createTelemetry } from './utils/otel'; const sdk = createTelemetry({ serviceName: 'my-api' }); ``` -------------------------------- ### Utility Functions Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/modules.html Utility functions for configuration loading and stream creation. ```APIDOC ## findConfigFile ### Description Finds the configuration file for the logger. ### Method [Function Signature] `findConfigFile(): string | undefined` ### Parameters None ### Request Example ```typescript const configFile = findConfigFile(); ``` ### Response #### Success Response (Path to config file) - **configFile** (string | undefined) - The path to the configuration file, or undefined if not found. ## loadConfigFromFile ### Description Loads logger configuration from a specified file path. ### Method [Function Signature] `loadConfigFromFile(filePath: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript loadConfigFromFile('config.json').then(config => { console.log(config); }); ``` ### Response #### Success Response (Logger configuration) - **config** (WonderLoggerConfig) - The loaded logger configuration. ## loadConfig ### Description Loads the logger configuration, searching for a config file if no path is provided. ### Method [Function Signature] `loadConfig(filePath?: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript loadConfig().then(config => { console.log(config); }); ``` ### Response #### Success Response (Logger configuration) - **config** (WonderLoggerConfig) - The loaded logger configuration. ## createMorganStream ### Description Creates a stream object compatible with the 'morgan' HTTP request logger middleware. ### Method [Function Signature] `createMorganStream(): NodeJS.WritableStream` ### Parameters None ### Request Example ```typescript import morgan from 'morgan'; const logger = createLogger(); const morganStream = createMorganStream(); app.use(morgan('combined', { stream: morganStream })); ``` ### Response #### Success Response (Writable stream) - **stream** (NodeJS.WritableStream) - A stream object for morgan. ## withTraceContext ### Description Wraps a function to include trace context from the current span. ### Method [Function Signature] `withTraceContext any>(fn: T): T` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const tracedFunction = withTraceContext((data) => { console.log('Processing with trace context:', data); }); tracedFunction('some data'); ``` ### Response #### Success Response (Wrapped function) - **function** (T) - The function wrapped with trace context propagation. ## withSpan ### Description Creates a new span and executes the provided function within its context. ### Method [Function Signature] `withSpan(spanName: string, fn: () => T): T` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript withSpan('my-operation', () => { // Code to be executed within a span console.log('Executing operation...'); }); ``` ### Response #### Success Response (Return value of the function) - **result** (T) - The return value of the executed function. ``` -------------------------------- ### Express Application Instrumentation (TypeScript) Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/media/README-1.md Provides an example of integrating wonder-logger telemetry into an Express.js application. It shows how to initialize telemetry early in the application lifecycle and use `withSpan` to instrument specific request handlers. The example configures tracing and metrics exporters. ```typescript import express from 'express' import { createTelemetry, withSpan } from './utils/otel' // Initialize telemetry BEFORE creating Express app createTelemetry({ serviceName: 'my-express-api', serviceVersion: '1.0.0', tracing: { exporter: 'otlp' }, metrics: { port: 9090 } }) const app = express() app.get('/users/:id', async (req, res) => { const user = await withSpan('fetch-user', async () => { return await db.users.findById(req.params.id) }) res.json(user) }) app.listen(3000) ``` -------------------------------- ### Example Validation Errors (Text) Source: https://github.com/jenova-marie/wonder-logger/blob/main/src/utils/config/README.md Provides examples of common configuration validation error messages produced by Zod, illustrating issues like missing required fields, invalid enum values, incorrect data types, and out-of-range values. ```text Config validation failed: - service.name: Service name is required Config validation failed: - logger.level: Invalid enum value. Expected 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'silent', received 'verbose' Config validation failed: - otel.tracing.sampleRate: Expected number, received string Config validation failed: - otel.tracing.sampleRate: Number must be between 0 and 1 ``` -------------------------------- ### Initialize Theme and App Display in JavaScript Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/functions/disposeMemoryStore.html This snippet initializes the application's theme based on local storage and controls the initial display of the body element. It sets the theme, hides the body, and then reveals it after a short delay, optionally showing the application page if available. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display = "none"; setTimeout(() => { window.app ? app.showPage() : document.body.style.removeProperty("display"); }, 500); ``` -------------------------------- ### Creating Logger and Telemetry from Configuration (JavaScript) Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/index.html Shows how to programmatically create a logger and telemetry instance using Wonder Logger's configuration functions. It assumes a `wonder-logger.yaml` file is present for the configuration. ```javascript import { createLoggerFromConfig, createTelemetryFromConfig } from 'wonder-logger'; // Assumes a wonder-logger.yaml file exists in the project root const sdk = createTelemetryFromConfig(); const logger = createLoggerFromConfig(); logger.info('Logger and telemetry initialized from config'); ``` -------------------------------- ### Utility and Helper Functions Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/modules.html Utility functions for configuration loading and integration with other libraries. ```APIDOC ## Utility and Helper Functions ### `findConfigFile(fileName)` **Description**: Searches for a configuration file in common locations. **Method**: `function` **Parameters**: #### Path Parameters - `fileName` (string) - Optional - The name of the configuration file to search for. Defaults to `DEFAULT_CONFIG_FILE`. ### `createMorganStream(logger)` **Description**: Creates a stream compatible with the 'morgan' HTTP request logger middleware. **Method**: `function` **Parameters**: #### Request Body - `logger` (object) - Required - An instance of a Wonder Logger. ### `filterByLevel(level)` **Description**: Returns a filter function that checks if a log entry's level is greater than or equal to the specified level. **Method**: `function` **Parameters**: #### Path Parameters - `level` (string) - Required - The minimum log level (e.g., 'info', 'warn', 'error'). ### `filterSince(timestamp)` **Description**: Returns a filter function that checks if a log entry occurred after the specified timestamp. **Method**: `function` **Parameters**: #### Path Parameters - `timestamp` (string | Date | number) - Required - The timestamp to filter logs from. ### `withBackpressure(options)` **Description**: Applies backpressure handling to a stream or transport. **Method**: `function` **Parameters**: #### Request Body - `options` (object) - Required - Backpressure options. - See `BackpressureOptions` interface for structure. ``` -------------------------------- ### Check Results Before Accessing Values Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/ERROR_HANDLING.md Illustrates the importance of checking the success status of a Result before accessing its value. The 'BAD' example shows a direct access that can lead to runtime errors, while the 'GOOD' example demonstrates safe access after a success check. ```typescript // ❌ BAD - Assumes success const config = loadConfig().value // Crashes if error! // ✅ GOOD - Check first const result = loadConfig() if (!result.ok) { console.error('Config failed:', result.error) process.exit(1) } const config = result.value ``` -------------------------------- ### Pattern Match on Specific Error Kinds Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/ERROR_HANDLING.md Highlights the benefit of handling different error types specifically. The 'BAD' example uses generic error handling, while the 'GOOD' example employs a switch statement on `error.kind` to provide tailored responses to different error scenarios. ```typescript // ❌ BAD - Generic error handling if (!result.ok) { console.error('Error:', result.error.message) } // ✅ GOOD - Specific handling if (!result.ok) { switch (result.error.kind) { case 'FileNotFound': // Handle missing file break case 'InvalidYAML': // Handle syntax error break default: // Handle unexpected errors } } ``` -------------------------------- ### YAML Configuration for Web Servers Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/CONFIGURATION.md Example YAML configuration file for web servers or long-running applications. It defines service details, logger settings (level, transports), and OpenTelemetry (otel) configuration. Environment variables can be used for dynamic values. ```yaml service: name: ${SERVICE_NAME:-my-api} version: ${SERVICE_VERSION:-1.0.0} environment: ${NODE_ENV:-development} logger: enabled: true # Boolean literal (NOT ${LOGGER_ENABLED:-true}) level: ${LOG_LEVEL:-info} transports: - type: console pretty: false # Boolean literal (NOT ${LOG_PRETTY:-false}) - type: file dir: ./logs fileName: app.log sync: false # Async mode for better throughput otel: enabled: true # Boolean literal (NOT ${OTEL_ENABLED:-true}) tracing: enabled: true exporter: otlp endpoint: ${OTEL_TRACES_ENDPOINT:-http://localhost:4318/v1/traces} ``` -------------------------------- ### Example Usage of loadConfig with Error Handling Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/media/README-2.md Provides a practical example of loading configuration using `loadConfig` within a try-catch block to handle potential errors during the loading or validation process. It logs the service name upon successful loading or prints an error message and exits if loading fails. ```typescript import { loadConfig } from '@recoverysky/wonder-logger' try { const config = loadConfig() console.log('Config loaded:', config.service.name) } catch (error) { console.error('Failed to load config:', error) process.exit(1) } ``` -------------------------------- ### Running Wonder Logger Tests with pnpm Commands Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/TESTING.md Provides bash commands for executing tests in a project utilizing Wonder Logger and pnpm. It covers running all tests, tests by category (unit, integration, e2e), running tests with coverage, and enabling watch mode for continuous testing. These commands are essential for maintaining code quality and verifying functionality. ```bash # All tests pnpm test # By category pnpm test:unit pnpm test:integration pnpm test:e2e # With coverage pnpm test:coverage pnpm test:unit:coverage # Watch mode pnpm test:watch ``` -------------------------------- ### Propagate Results Instead of Throwing Exceptions Source: https://github.com/jenova-marie/wonder-logger/blob/main/content/ERROR_HANDLING.md Contrasts two approaches to error handling in functions. The 'BAD' example converts errors into exceptions, disrupting control flow. The 'GOOD' example demonstrates returning a Result type, allowing errors to be propagated gracefully up the call stack. ```typescript // ❌ BAD - Convert to exceptions function init(): App { const result = loadConfig() if (!result.ok) throw new Error(result.error.message) return new App(result.value) } // ✅ GOOD - Return Result function init(): Result { const result = loadConfig() if (!result.ok) return result // Propagate error return ok(new App(result.value)) } ``` -------------------------------- ### Migration: New Modular Telemetry Factory Source: https://github.com/jenova-marie/wonder-logger/blob/main/src/utils/otel/README.md Demonstrates the new modular factory pattern for telemetry initialization. It covers creating the SDK, accessing tracer and meter, and using the `withSpan` function. ```typescript import { createTelemetry, withSpan, TelemetrySDK } from './utils/otel' // Returns SDK wrapper, not raw NodeSDK const sdk: TelemetrySDK = createTelemetry({ serviceName: 'my-api' }) // SDK methods await sdk.forceFlush() // Force flush (testing) await sdk.shutdown() // Graceful shutdown sdk.start() // Start (called automatically) // Tracer and meter available via @opentelemetry/api import { trace, metrics } from '@opentelemetry/api' const tracer = trace.getTracer('my-tracer') const meter = metrics.getMeter('my-meter') await withSpan('operation', async () => { // ... }) ``` -------------------------------- ### Log Structured Data Instead of String Concatenation (TypeScript) Source: https://github.com/jenova-marie/wonder-logger/blob/main/docs/media/README.md Highlights the importance of logging structured data (objects) rather than concatenating strings for better machine-parseability, queryability in systems like Loki/Elasticsearch, and type safety with TypeScript. It contrasts a 'bad' string concatenation example with a 'good' structured data example. ```typescript logger.info({ userId, ip }, 'User logged in') ``` -------------------------------- ### Build and Test Wonder Logger Project Source: https://github.com/jenova-marie/wonder-logger/blob/main/CONTRIBUTING.md Commands to build the Wonder Logger project and run its unit and integration tests. These commands are essential for verifying code changes and ensuring project integrity. ```bash pnpm build pnpm test:unit pnpm test:integration ``` -------------------------------- ### Load Wonder Logger Configuration Programmatically (TypeScript) Source: https://github.com/jenova-marie/wonder-logger/blob/main/README.md TypeScript code demonstrating how to initialize wonder-logger and its telemetry components by loading configuration from a `wonder-logger.yaml` file in the project root. This sets up the logger and telemetry SDK for application use. ```typescript import { createLoggerFromConfig, createTelemetryFromConfig } from 'wonder-logger' // Load from wonder-logger.yaml in project root const sdk = createTelemetryFromConfig() const logger = createLoggerFromConfig() // Now start logging with full observability logger.info('Application started') logger.info({ userId: 123 }, 'User logged in') ```