logsmith
A declarative structured-logging library for Dart, inspired by Go's log/slog and charmbracelet/log.
logsmith is terminal-first but format-aware: one immutable Record model can render as themed terminal output, JSON, YAML, TOML, Mace, or logfmt, with explicit stdout/stderr routing and testable sinks.
Features
- Typed structured attributes, including nested maps and lists
- Three logger kinds: single-line, multiline, and boxed terminal output
- Six emitters: text, JSON, YAML, TOML, Mace, and logfmt
- Level-based stdout/stderr routing with custom stream policies
- Fifty bundled terminal themes with dark/light pairing, OSC-11 adaptive selection, and color-depth quantization
NO_COLOR, force-color, terminal-capability, and machine-consumer detection- File and rotating-file sinks, plus bounded asynchronous delivery
- Opt-in caller capture, isolate identity, and terminal-safe value truncation
- Pure Dart runtime; no Flutter dependency
Getting started
Requires Dart 3.13.2 or later. Add the package:
dart pub add logsmith
Then create a logger with a handler:
import 'package:logsmith/logsmith.dart';
void main() {
const emitter = Emitter();
final terminal = Handler(
format: (record) => emitter.text(record),
);
final log = Logger.singleLine(name: 'billing', handlers: [terminal]);
log.info(
'invoice charged',
attrs: {
'invoice_id': 'inv-1024',
'amount': 19.99,
'currency': 'USD',
},
);
log.withAttrs({'request_id': 'req-42'}).success('charge confirmed');
}
Formats
Every emitter method is a formatter seam and can be passed to a handler:
const emitter = Emitter();
final jsonHandler = Handler(format: emitter.json);
final logfmtHandler = Handler(format: emitter.logfmt);
final prettyJsonHandler = Handler(
format: (record) => emitter.json(record, indent: 2),
);
The available methods are text, json, yaml, toml, mace, and logfmt. Structured formats preserve nested attrs. text and logfmt can render boxed records inside border frames.
Adaptive terminal themes
Handler.adaptiveText probes the terminal background with OSC-11 and chooses the dark or light theme from a ThemePair:
final terminal = Handler.adaptiveText(
pair: Themes.defaultPair,
);
final log = Logger.singleLine(handlers: [terminal]);
The probe is skipped for non-terminal, color-disabled, and detected machine-consumer output. It listens on stdin for at most 50ms and may temporarily switch the terminal out of line/echo mode so the response can arrive without an Enter keypress. Initial records are buffered briefly, COLORFGBG is the fallback hint, and fatal records are never delayed. Because probing temporarily reads stdin, applications with their own interactive input loop may prefer explicit selection:
final theme = Themes.defaultPair.forVariant(ThemeVariant.dark);
final terminal = Handler(format: (r) => const Emitter().text(r, theme: theme));
Terminal-only truncation and isolate identity
Long scalar attribute values can be truncated for human terminal output without changing structured formats:
final terminal = Handler(
format: (record) => emitter.text(record, maxValueLength: 120),
);
The limit is measured in terminal cells, includes the ellipsis marker, and applies only to terminal text. JSON, YAML, TOML, Mace, and logfmt always retain complete values.
Isolate identity is opt-in:
final log = Logger.singleLine(
handlers: [terminal],
captureIsolate: true,
);
Terminal output renders a compact identity through the theme's isolate slot. Structured formats receive an isolate object containing a process-local numeric token, the VM service ID when available, and the debug name when present. Dart does not guarantee ordinal isolate IDs, so the numeric token is stable identity data rather than a monotonic sequence.
Routing and files
By default, records below warning go to the primary sink and warning-or-higher records go to stderr. Use StreamPolicy to choose routing explicitly:
import 'dart:io';
import 'package:logsmith/logsmith.dart';
Future<void> main() async {
const emitter = Emitter();
await Directory('logs').create(recursive: true);
final file = FileSink('logs/app.log', flushOn: Level.error);
final fileHandler = Handler(
format: emitter.json,
policy: StreamPolicy.always(file),
sink: file,
);
final terminalHandler = Handler(format: (r) => emitter.text(r));
final log = Logger.multiline(
name: 'worker',
handlers: [terminalHandler, fileHandler],
);
log.warning('retrying upstream', attrs: {'attempt': 2});
log.error('upstream failed', error: StateError('connection reset'));
await file.close();
}
RotatingFileSink adds size-based rotation. AsyncHandler provides a bounded, drop-oldest queue around another handler:
final async = AsyncHandler(fileHandler, capacity: 1024);
final log = Logger.singleLine(handlers: [async.handler]);
// Before process exit:
await async.close();
Examples
Run the API tour:
dart run example/logsmith_example.dart
In a source checkout, generate and browse the theme/format showcase:
dart run example/showcase.dart
dart run example/view_showcase.dart
Project status
logsmith 1.0.0 is the first stable release. The v1 behavior contract is specified in docs/spec-v1.md; color-policy decisions are documented in docs/adr/0001-machine-consumer-color-detection.md.
License
See LICENSE.
Libraries
- logsmith
- logsmith — a declarative structured-logging library for Dart.