Language Page

ktrace for Java

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

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

Karma Trace Logging SDK

ktools-java/ktrace/README.md

ktrace is the Java tracing and logging SDK in the ktools ecosystem.

It provides:

  • namespaced channel tracing via TraceLogger.trace(...)
  • always-visible operational logging via TraceLogger.info/warn/error(...)
  • executable-facing channel filtering and formatting via Logger
  • kcli inline parser integration through Logger.makeInlineParser(...)

Documentation

Build SDK

ktrace depends on the sibling Java kcli SDK. Build ktools-java/kcli first, or use the Java workspace root to build both in dependency order:

cd ..
kbuild --batch --build-latest
cd ktrace
kbuild --build-latest

SDK output:

  • build/latest/sdk/classes

Build And Test Demos

If kcli has not been built yet in this workspace, prefer the batch build from ktools-java/ first so the dependency SDK is present.

# Builds the SDK plus demos listed in .kbuild.json build.defaults.demos.
kbuild --build-latest

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

./build/latest/tests/run-tests

Demos:

  • Bootstrap compile/link check: demo/bootstrap/
  • SDKs: demo/sdk/{alpha,beta,gamma}
  • Executables: demo/exe/{core,omega}

Trace CLI examples:

./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

import ktrace.Logger;
import ktrace.TraceColors;
import ktrace.TraceLogger;

Logger logger = new Logger();

TraceLogger appTrace = new TraceLogger("core");
appTrace.addChannel("app", TraceColors.color("BrightCyan"));
appTrace.addChannel("startup", TraceColors.color("BrightYellow"));

logger.addTraceLogger(appTrace);
logger.enableChannel(appTrace, ".app");
appTrace.trace("app", "core initialized");

CLI Integration

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

Ktrace Java Documentation

ktools-java/ktrace/docs/index.md

ktrace is the Java tracing and logging SDK in the ktools ecosystem.

It is built around two public runtime types:

  • TraceLogger for library-facing namespaced trace and log emission
  • Logger for executable-facing channel registration, selector control, formatting, and kcli integration

Start Here

Typical Flow

import kcli.Parser;
import ktrace.Logger;
import ktrace.TraceColors;
import ktrace.TraceLogger;

Logger logger = new Logger();

TraceLogger appTrace = new TraceLogger("core");
appTrace.addChannel("app", TraceColors.color("BrightCyan"));
appTrace.addChannel("startup", TraceColors.color("BrightYellow"));

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

Parser parser = new Parser();
parser.addInlineParser(logger.makeInlineParser(appTrace));
parser.parseOrExit(args);

appTrace.trace("app", "startup complete");

Core Concepts

TraceLogger

  • owns one explicit namespace such as core, alpha, or omega
  • registers valid channels for that namespace
  • emits channel-based trace output through trace(...)
  • emits always-visible operational log output through info/warn/error(...)

Logger

  • imports one or more TraceLogger instances
  • maintains the central registry of known namespaces and channels
  • enables and disables channels by exact selector or selector expression
  • controls output formatting such as files, functions, and timestamps
  • exposes trace CLI controls with makeInlineParser(...)

Selector

  • identifies one or more registered channels using forms such as .app, alpha.net, *.*, or *.{net,io}

Build And Explore

ktrace depends on the sibling Java kcli SDK. If that SDK is not already built, start from the Java workspace root so both repos build in dependency order:

cd ..
kbuild --batch --build-latest
cd ktrace
kbuild --help
kbuild --build-latest
./build/latest/tests/run-tests
./demo/exe/core/build/latest/test --trace '*.*'
./demo/exe/omega/build/latest/test --trace '*.{net,io}'

Working References

API Guide

ktools-java/ktrace/docs/api.md

This page summarizes the public Java API in:

Core Types

Type Purpose
TraceLogger Library-facing source object for one explicit namespace.
Logger Executable-facing registry, selector filter, formatter, and CLI integration surface.
OutputOptions Controls file, line, function, and timestamp output formatting.
TraceColors Resolves named trace colors and exposes the default color constant.

TraceLogger

Construction

TraceLogger trace = new TraceLogger("alpha");

Rules:

  • the namespace is required
  • namespaces use identifier-style tokens such as alpha, core, or beta-2
  • invalid namespaces throw IllegalArgumentException

Channel Registration

trace.addChannel("net");
trace.addChannel("net.alpha");
trace.addChannel("cache", TraceColors.color("Gold3"));

Rules:

  • channels are explicitly registered before use
  • nested channels require their parent channel to exist first
  • duplicate channel registration is allowed when colors are compatible
  • conflicting explicit colors are rejected

Trace Output

trace.trace("net", "starting request {} for {}", requestId, host);
trace.traceChanged("cache", cacheKey, "cache state changed");

trace(...)

  • emits only when the imported Logger has that channel enabled
  • validates the channel name before emitting

traceChanged(...)

  • suppresses repeated emission for the same call site and key value
  • emits again when the key changes at that same site

Operational Logging

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

These methods:

  • do not depend on channel enablement
  • still include the trace namespace
  • still obey current OutputOptions

Logger

Lifecycle

Logger logger = new Logger();
logger.addTraceLogger(appTrace);
logger.addTraceLogger(alphaTrace);

The Logger:

  • imports one or more TraceLogger instances
  • owns the central registry of registered channels
  • rejects attaching the same TraceLogger handle to different Logger instances

Exact Channel Control

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

logger.disableChannel("alpha.net");
logger.disableChannel(appTrace, ".app");

Exact selectors may use:

  • namespace.channel
  • .channel when a local namespace is supplied

If an exact selector names an unregistered channel:

  • the call succeeds
  • a warning log line is emitted
  • the channel remains disabled

Selector-List Control

logger.enableChannels("*.*");
logger.enableChannels(appTrace, ".app,alpha.net");

logger.disableChannels("alpha.*");

These methods:

  • accept comma-separated selector expressions
  • resolve only against channels already registered with this Logger
  • ignore unresolved selectors with warning output

Query Surface

boolean enabled = logger.shouldTraceChannel("alpha.net");
List<String> namespaces = logger.getNamespaces();
List<String> channels = logger.getChannels("alpha");

shouldTraceChannel(...) returns false for:

  • invalid selectors
  • unregistered channels
  • registered but currently disabled channels

Output Options

logger.setOutputOptions(new OutputOptions(true, true, true, true));
OutputOptions options = logger.getOutputOptions();

Fields:

Field Meaning
filenames Include source file labels.
lineNumbers Include line numbers when file labels are enabled.
functionNames Include method names when file labels are enabled.
timestamps Include compact epoch-second timestamps.

If filenames is false, line and function labels are suppressed.

CLI Integration

InlineParser parser = logger.makeInlineParser(appTrace);
InlineParser custom = logger.makeInlineParser(appTrace, "trace");

The generated inline parser supports:

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

TraceColors

int cyan = TraceColors.color("BrightCyan");
int defaultColor = TraceColors.DEFAULT;

Use TraceColors.color(...) when you want named colors in demo or application setup code. Unknown names throw IllegalArgumentException.

Formatting Rules

Message formatting supports:

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

Examples:

trace.trace("app", "value {} {}", 7, "done");
trace.warn("escaped {{}}");

Unsupported format tokens such as {:x} throw IllegalArgumentException.

Examples

ktools-java/ktrace/docs/examples.md

This page shows a few common Java ktrace patterns. For complete working examples, also see:

Minimal Executable

import kcli.Parser;
import ktrace.Logger;
import ktrace.TraceLogger;

Logger logger = new Logger();
TraceLogger trace = new TraceLogger("app");
trace.addChannel("startup");

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

Parser parser = new Parser();
parser.addInlineParser(logger.makeInlineParser(trace));
parser.parseOrExit(args);

trace.trace("startup", "application started");

Imported SDK Trace Logger

Library code:

public final class AlphaSdk {
    public static TraceLogger getTraceLogger() {
        TraceLogger logger = new TraceLogger("alpha");
        logger.addChannel("net");
        logger.addChannel("cache");
        return logger;
    }
}

Executable code:

Logger logger = new Logger();
TraceLogger appTrace = new TraceLogger("core");
appTrace.addChannel("app");

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

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

Local Namespace Selectors

TraceLogger appTrace = new TraceLogger("omega");
appTrace.addChannel("app");
appTrace.addChannel("deep");
appTrace.addChannel("deep.branch");

logger.addTraceLogger(appTrace);

logger.enableChannel(appTrace, ".app");
logger.enableChannels(appTrace, ".app,.deep.branch");

Using the local-trace overload lets leading-dot selectors resolve against the correct namespace.

Output Formatting

logger.setOutputOptions(new OutputOptions(true, true, true, true));

trace.trace("app", "formatted trace line");
trace.warn("formatted warning");

This enables:

  • source file labels
  • line numbers
  • method names
  • timestamps

traceChanged(...)

trace.addChannel("state");
logger.addTraceLogger(trace);
logger.enableChannel("app.state");

trace.traceChanged("state", currentState, "state changed to {}", currentState);

This is useful when:

  • the same polling or update site runs frequently
  • you only want a log line when the observed key changes

Trace CLI

Parser parser = new Parser();
parser.addInlineParser(logger.makeInlineParser(appTrace));
parser.parseOrExit(args);

Examples:

--trace '.app'
--trace '*.*'
--trace '*.{net,io}'
--trace-files
--trace-functions
--trace-timestamps
--trace-channels

Selector And CLI Behavior

ktools-java/ktrace/docs/selectors.md

This page summarizes selector matching and the generated --trace-* CLI behavior.

Exact Selectors

Exact channel APIs:

  • enableChannel(...)
  • disableChannel(...)
  • shouldTraceChannel(...)

Accepted forms:

  • namespace.channel
  • namespace.channel.sub
  • .channel
  • .channel.sub

Rules:

  • .channel requires a local namespace, such as enableChannel(appTrace, ".app")
  • exact selectors must point to registered channels to become enabled
  • invalid exact selectors throw IllegalArgumentException in mutating APIs
  • shouldTraceChannel(...) returns false instead of throwing

Selector Lists

Selector-list APIs:

  • enableChannels(...)
  • disableChannels(...)

Accepted forms include:

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

Rules:

  • input is comma-separated
  • brace expansion is supported
  • matching is performed against currently registered channels only
  • unmatched selectors are reported as warnings
  • empty or whitespace-only selector lists are rejected

Depth Semantics

Channel depth is limited to three segments:

  • top
  • top.child
  • top.child.leaf

Wildcard meaning:

Selector Meaning
*.* All top-level namespace channels.
*.*.* All channels up to depth 2.
*.*.*.* All channels up to depth 3.

*.{net,io} matches only those exact top-level channel names across all namespaces.

Generated Trace CLI

Logger.makeInlineParser(localTrace) creates an inline root that can be attached to kcli.Parser:

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

This enables:

--trace
--trace '*.*'
--trace '.app'
--trace-examples
--trace-namespaces
--trace-channels
--trace-colors
--trace-files
--trace-functions
--trace-timestamps

Bare Root

--trace

Behavior:

  • prints inline help
  • does not enable any channels

Root Value

--trace '.app'
--trace '*.{net,io}'

Behavior:

  • resolves the selector expression
  • enables matching registered channels
  • warns for unmatched selectors

Formatting Options

These toggle Logger output formatting:

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

Effects:

  • --trace-files enables file and line labels
  • --trace-functions enables file, line, and method labels
  • --trace-timestamps enables timestamps for both trace and operational logs

Failure Model

Invalid --trace <selector> input is surfaced through kcli as a normal option failure. For example:

[error] [cli] option '--trace': Invalid trace selector: '*' (did you mean '.*'?)

Unknown generated options such as --trace-lines are treated as ordinary unknown kcli options.