Language Page

ktrace for JavaScript

This page is assembled from markdown in ktools-javascript. GitHub links point to the workspace repo and the relevant source files or directories.

5 markdown sections
QM-Code/ktools-javascript primary repo
HTML static output

Karma Trace Logging SDK (JavaScript)

ktools-javascript/ktrace/README.md

Trace logging SDK with:

  • namespaced channel tracing via TraceLogger.trace(...)
  • always-visible operational logging via TraceLogger.info/warn/error(...)
  • a library-facing TraceLogger source object
  • an executable-facing Logger registry, filter, formatter, and CLI bridge

Documentation

Build SDK

kbuild --build-latest

SDK output:

  • build/latest/sdk/src/ktrace
  • build/latest/sdk/share/kbuild-javascript-sdk.json

Build And Test Demos

# Builds SDK plus .kbuild.json "build.defaults.demos".
kbuild --build-latest

# Explicit demo-only run (uses build.demos when no args are provided).
kbuild --build-demos

./demo/exe/core/build/latest/test

Demos:

  • Bootstrap load/use check: demo/bootstrap/
  • SDK modules: demo/sdk/{alpha,beta,gamma}.js
  • Executables: demo/exe/{core,omega}

Trace CLI examples:

./demo/bootstrap/build/latest/bootstrap
./demo/exe/core/build/latest/test --trace
./demo/exe/core/build/latest/test --trace '.*'
./demo/exe/omega/build/latest/test --trace '*.*'
./demo/exe/omega/build/latest/test --trace '*.*.*.*'
./demo/exe/omega/build/latest/test --trace '*.{net,io}'
./demo/exe/omega/build/latest/test --trace-namespaces
./demo/exe/omega/build/latest/test --trace-channels
./demo/exe/omega/build/latest/test --trace-colors

API Model

TraceLogger is the namespace-bearing source object. Construct it with an explicit namespace and declare channels on it:

const trace = new ktrace.TraceLogger("alpha");
trace.addChannel("net", ktrace.Color("DeepSkyBlue1"));
trace.addChannel("cache", ktrace.Color("Gold3"));

SDKs should usually expose a shared logger from getTraceLogger():

function getTraceLogger() {
    if (!getTraceLogger._logger) {
        const trace = new ktrace.TraceLogger("alpha");
        trace.addChannel("net", ktrace.Color("DeepSkyBlue1"));
        trace.addChannel("cache", ktrace.Color("Gold3"));
        getTraceLogger._logger = trace;
    }
    return getTraceLogger._logger;
}

Logger is the executable-facing runtime. It imports one or more TraceLoggers, maintains the central channel registry, and owns selector filtering, formatting, and final output:

const logger = new ktrace.Logger();

const appTrace = new ktrace.TraceLogger("core");
appTrace.addChannel("app", ktrace.Color("BrightCyan"));
appTrace.addChannel("startup", ktrace.Color("BrightYellow"));

logger.addTraceLogger(appTrace);
logger.addTraceLogger(alpha.getTraceLogger());

Logging APIs

Channel-based trace output:

trace.trace("channel", "message {}", value);
trace.traceChanged("channel", key, "message {}", value);

Always-visible operational logging:

trace.info("message");
trace.warn("configuration file '{}' was not found", path);
trace.error("fatal startup failure");

Operational logging is independent of channel enablement. It is still namespaced and uses the same formatting options as trace output.

Message formatting supports sequential {} placeholders and escaped braces {{ and }}.

Color names use the shared extended palette exposed by --trace-colors, which now matches the JavaScript implementation's supported catalog.

CLI Integration

The inline parser is logger-bound rather than global. Pass the executable's local TraceLogger so leading-dot selectors resolve against the right namespace:

const logger = new ktrace.Logger();
const appTrace = new ktrace.TraceLogger("core");
appTrace.addChannel("app", ktrace.Color("BrightCyan"));

logger.addTraceLogger(appTrace);

const parser = new kcli.Parser();
parser.addInlineParser(logger.makeInlineParser(appTrace));

parser.parseOrExit(process.argv.length, process.argv);

Channel Expression Forms

Single-selector APIs on ktrace.Logger:

  • .channel[.sub[.sub]] for a local channel in the provided local namespace
  • namespace.channel[.sub[.sub]] for an explicit namespace

List APIs on ktrace.Logger:

  • enableChannels(...)
  • disableChannels(...)
  • list APIs accept selector patterns such as *, {}, and CSV
  • list APIs resolve selectors against the channels currently registered at call time
  • leading-dot selectors in list APIs resolve against the provided local namespace
  • empty or whitespace-only selector lists are rejected
  • unregistered channels remain disabled and do not emit, even if a selector pattern would otherwise match

Examples:

  • logger.enableChannel(appTrace, ".app");
  • logger.enableChannel("alpha.net");
  • logger.enableChannels("alpha.*,{beta,gamma}.net.*");
  • logger.enableChannels(appTrace, ".net.*,otherapp.scheduler.tick");
  • logger.disableChannels(appTrace, ".cache");

Formatting options:

  • --trace-files
  • --trace-functions
  • --trace-timestamps

These affect both trace(...) output and info/warn/error(...) output.

Build And Test

kbuild --build-latest
kbuild --build-demos

Direct source-level tests:

node --test tests/*.js demo/tests/*.js

ktrace JavaScript Overview

ktools-javascript/ktrace/docs/index.md

ktrace is the JavaScript tracing and operational logging SDK in the ktools stack.

It preserves the same runtime model used by the C++ implementation:

  • library-owned TraceLogger instances define namespaces and channels
  • executable-owned Logger instances aggregate those trace sources
  • selector-based enablement decides which trace channels emit
  • info(), warn(), and error() remain visible independent of selectors
  • kcli integration exposes trace controls through --trace-*

Quick Start

"use strict";

const kcli = require("../src/kcli");
const ktrace = require("../src/ktrace");

const logger = new ktrace.Logger();
const trace = new ktrace.TraceLogger("core");

trace.addChannel("app", ktrace.Color("BrightCyan"));
trace.addChannel("startup", ktrace.Color("BrightYellow"));

logger.addTraceLogger(trace);
logger.enableChannel(trace, ".app");

const parser = new kcli.Parser();
parser.addInlineParser(logger.makeInlineParser(trace));
parser.parseOrExit(process.argv.length, process.argv);

trace.trace("app", "cli initialized");
trace.info("service started");

What To Read Next

Demo Programs

The built demo wrappers are the quickest parity check:

kbuild --build-latest
./demo/exe/core/build/latest/test --trace '.*'
./demo/exe/omega/build/latest/test --trace '*.{net,io}'
./demo/exe/omega/build/latest/test --trace-colors

ktrace JavaScript API

ktools-javascript/ktrace/docs/api.md

ktrace exposes three public exports:

  • TraceLogger
  • Logger
  • Color(name)

Import

From this repo:

const ktrace = require("../src/ktrace");

Color(name)

Validates and returns a supported color token.

const accent = ktrace.Color("BrightCyan");

Color(name) accepts the shared extended palette exposed by --trace-colors. Representative examples include:

  • Default
  • BrightCyan
  • DeepSkyBlue1
  • Gold3
  • MediumSpringGreen
  • Orange3
  • MediumOrchid1
  • LightSkyBlue1

TraceLogger

Namespace-bearing trace source used by libraries and applications.

Constructor

const trace = new ktrace.TraceLogger("alpha");

Methods

addChannel(channel, color = "Default")

Registers a channel path inside the logger namespace.

trace.addChannel("net", ktrace.Color("DeepSkyBlue1"));
trace.addChannel("cache");
trace.addChannel("cache.delta");

getNamespace()

Returns the logger namespace.

shouldTraceChannel(channel)

Returns whether the attached runtime currently enables the channel.

trace(channel, formatText, ...args)

Emits channel-based trace output if the channel is currently enabled.

trace.trace("net", "connecting to {}", host);

traceChanged(channel, key, formatText, ...args)

Suppresses repeated output at one call site until key changes.

trace.traceChanged("cache", revision, "cache revision {}", revision);

info(formatText, ...args)

Emits always-visible informational output.

warn(formatText, ...args)

Emits always-visible warning output.

error(formatText, ...args)

Emits always-visible error output.

Operational logging does not depend on channel enablement.

Logger

Executable-facing runtime that aggregates trace loggers, applies selectors, and controls formatting.

Constructor

const logger = new ktrace.Logger();

Methods

addTraceLogger(traceLogger)

Attaches a TraceLogger and imports its registered namespace/channels.

logger.addTraceLogger(appTrace);
logger.addTraceLogger(alphaTrace);

enableChannel(channel, localNamespace?)

Enables one exact qualified channel, for example:

logger.enableChannel("alpha.net");
logger.enableChannel(".app", "core");
logger.enableChannel(appTrace, ".app");

enableChannels(selectorsCsv, localNamespace?)

Enables selector-based channel sets.

logger.enableChannels("*.*");
logger.enableChannels("*.{net,io}");
logger.enableChannels(".app,*.{net,io}", "omega");

The TraceLogger overload is also supported:

logger.enableChannels(appTrace, ".app");

disableChannel(channel, localNamespace?)

Disables one exact channel.

disableChannels(selectorsCsv, localNamespace?)

Disables selector-based channel sets.

The TraceLogger overload is also supported:

logger.disableChannels(appTrace, ".app");

shouldTraceChannel(channel, localNamespace?)

Returns whether a qualified or local channel is currently enabled.

logger.shouldTraceChannel("alpha.net");
logger.shouldTraceChannel(".app", "core");

setOutputOptions(options)

Configures output formatting.

Supported fields:

  • filenames
  • line_numbers
  • function_names
  • timestamps
logger.setOutputOptions({
    filenames: true,
    line_numbers: true,
    timestamps: true,
});

If function_names is enabled, filenames and line numbers are enabled automatically.

getOutputOptions()

Returns a copy of the current output options.

getNamespaces()

Returns all registered namespaces in sorted order.

getChannels(traceNamespace)

Returns all registered channels for one namespace in sorted order.

makeInlineParser(localTraceLogger, traceRoot = "trace")

Builds a kcli.InlineParser for trace CLI integration.

const parser = new kcli.Parser();
parser.addInlineParser(logger.makeInlineParser(appTrace));

The generated inline parser supports:

  • --trace <selectors>
  • --trace-examples
  • --trace-namespaces
  • --trace-channels
  • --trace-colors
  • --trace-files
  • --trace-functions
  • --trace-timestamps

Selector Forms

Supported selector patterns include:

  • .app
  • alpha.net
  • *.*
  • *.*.*.*
  • *.{net,io}
  • {alpha,beta}.*

Leading-dot selectors resolve against the local namespace supplied to the logger method or to makeInlineParser().

Selectors only affect channels that were actually registered through addTraceLogger().

Formatting

ktrace uses sequential {} placeholders with escaped braces {{ and }}.

trace.info("loaded {} records from {{cache}}", count);

Typical Pattern

const kcli = require("../src/kcli");
const ktrace = require("../src/ktrace");

const logger = new ktrace.Logger();
const trace = new ktrace.TraceLogger("core");

trace.addChannel("app", ktrace.Color("BrightCyan"));
trace.addChannel("startup", ktrace.Color("BrightYellow"));

logger.addTraceLogger(trace);
logger.enableChannel(trace, ".app");

const parser = new kcli.Parser();
parser.addInlineParser(logger.makeInlineParser(trace));
parser.parseOrExit(process.argv.length, process.argv);

trace.trace("app", "cli initialized");
trace.info("service started");

Trace Behavior

ktools-javascript/ktrace/docs/behavior.md

This page captures the JavaScript ktrace behavior that matters in practice.

Runtime Model

ktrace splits responsibilities between two public types:

  • TraceLogger owns one namespace and its declared channels
  • Logger owns the executable-facing registry, selector state, formatting, and final output

Channels only become selectable after their TraceLogger is attached through logger.addTraceLogger(...).

Channel Enablement

Trace output from trace.trace(...) is emitted only when all of the following are true:

  • the TraceLogger is attached to a Logger
  • the channel was registered with addChannel(...)
  • the Logger currently has that qualified channel enabled

Operational logging from info(), warn(), and error() is always emitted once the TraceLogger is attached.

Selector Rules

Single-channel APIs accept:

  • .channel[.sub[.sub]] for local-namespace lookups
  • namespace.channel[.sub[.sub]] for explicit namespaces

Selector-list APIs accept comma-separated selector patterns including:

  • *.*
  • *.*.*.*
  • *.{net,io}
  • {alpha,beta}.*

Rules:

  • leading-dot selectors resolve against the provided local namespace
  • selector lists are matched only against channels already registered
  • unmatched selectors emit a warning and do not fail the parse
  • invalid selector syntax throws, which surfaces through kcli as a CLI error

Formatting

Message formatting supports:

  • sequential {} placeholders
  • escaped braces {{ and }}

It does not support fmt-style specifiers such as {:x}.

Output Options

Logger#setOutputOptions(...) supports:

  • filenames
  • line_numbers
  • function_names
  • timestamps

If function_names is enabled, filenames and line numbers are enabled automatically.

The makeInlineParser(...) helper exposes the corresponding CLI switches:

  • --trace-files
  • --trace-functions
  • --trace-timestamps

Color Names

Color(name) accepts the shared extended named palette used by the JavaScript implementation and listed by --trace-colors.

Representative examples:

  • BrightCyan
  • DeepSkyBlue1
  • MediumSpringGreen
  • Orange3
  • MediumOrchid1
  • LightSkyBlue1

Coverage

Current behavior is exercised by:

  • tests/test_ktrace_js.js
  • demo/tests/test_core_trace_cli.js
  • demo/tests/test_omega_trace_cli.js

Examples

ktools-javascript/ktrace/docs/examples.md

This page shows common JavaScript ktrace integration patterns.

For runnable examples, also see:

  • demo/sdk/alpha.js
  • demo/sdk/beta.js
  • demo/sdk/gamma.js
  • demo/exe/core/main.js
  • demo/exe/omega/main.js

Shared SDK Trace Source

const ktrace = require("../src/ktrace");

function getTraceLogger() {
    if (!getTraceLogger._logger) {
        const trace = new ktrace.TraceLogger("alpha");
        trace.addChannel("net", ktrace.Color("DeepSkyBlue1"));
        trace.addChannel("cache", ktrace.Color("Gold3"));
        getTraceLogger._logger = trace;
    }
    return getTraceLogger._logger;
}

Executable Logger With CLI Integration

const kcli = require("../src/kcli");
const ktrace = require("../src/ktrace");
const alpha = require("../demo/sdk/alpha");

const logger = new ktrace.Logger();
const trace = new ktrace.TraceLogger("core");

trace.addChannel("app", ktrace.Color("BrightCyan"));
trace.addChannel("startup", ktrace.Color("BrightYellow"));

logger.addTraceLogger(trace);
logger.addTraceLogger(alpha.getTraceLogger());

const parser = new kcli.Parser();
parser.addInlineParser(logger.makeInlineParser(trace));
parser.parseOrExit(process.argv.length, process.argv);

Selector Control

logger.enableChannel(trace, ".app");
logger.enableChannels("*.{net,io}");
logger.disableChannels(trace, ".startup");

Output Formatting

logger.setOutputOptions({
    filenames: true,
    line_numbers: true,
    timestamps: true,
});

Operational Logging

trace.trace("app", "accepted {} requests", count);
trace.info("service started");
trace.warn("retrying {}", url);
trace.error("startup failed for {}", serviceName);