logsmith

logsmith structured logging artwork

logsmith is a pure-Dart structured-logging library for command-line and server applications. It helps application developers keep useful event data separate from message text, then send each event to people at a terminal, machine consumers, files, or more than one destination. The examples below show the main logger workflows directly.

CI License: BSD-3-Clause

Documentation

How it works

A logger turns a call into a structured Record containing a level, message, timestamp, attributes, and optional diagnostic data such as an error and stack trace. Choose a logger for the destination; the logger handles event construction, formatting, routing, and delivery. Application code can depend on the shared Logger type instead of an output pipeline.

withAttrs returns a derived logger with persistent attributes. It does not mutate the original logger, and attributes passed at the call site override persistent values with the same key. Attribute values can be strings, numbers, booleans, dates, durations, URIs, nulls, and nested maps or iterables.

Terminal logging

Use TerminalLogger for human-readable text. Pick single-line, multiline, or boxed rendering at construction; terminal capability affects styling, not the output format.

import 'package:logsmith/logsmith.dart';

void main() {
  final log = TerminalLogger.singleLine(name: 'checkout');
  final request = log.withAttrs({'request_id': 'req-42'});

  request.info('request started', attrs: {'route': '/orders'});
  request.success(
    'order accepted',
    attrs: {'order_id': 'ord-7341', 'total': 42.50},
  );

  TerminalLogger.multiline(name: 'worker').warning(
    'upstream timed out\nretrying with a backoff',
    attrs: {'attempt': 2, 'delay': const Duration(milliseconds: 250)},
  );

  TerminalLogger.boxed(name: 'release').info('deployment complete');
}

Terminal color can be automatic, forced, or disabled. Passive theme selection is the default; opt into active background detection when desired:

final plain = TerminalLogger.singleLine(
  colorMode: TerminalColorMode.never,
);
final adaptive = TerminalLogger.singleLine(
  themeMode: TerminalThemeMode.adaptive,
);

Machine-readable logging

Use MachineLogger when output is consumed by a program, CI job, or pipe. It writes compact JSON Lines by default. Select logfmt explicitly when that format is more convenient; terminal detection never changes the chosen format.

final json = MachineLogger(name: 'audit');
json.info('user signed in', attrs: {
  'user_id': 42,
  'source': 'oauth',
});

final logfmt = MachineLogger.logfmt(name: 'audit');
logfmt.warning('login requires review', attrs: {
  'user_id': 42,
  'reason': 'new device',
});

Warnings and more severe levels go to stderr by default. Pass stderrThreshold: null to keep all records on stdout. A non-null jsonIndent produces pretty, multiline JSON values rather than JSON Lines.

File logging

FileLogger writes complete event frames. It supports JSON, text, logfmt, YAML, TOML, and Mace output, plus optional size- or time-based rotation. Create the parent directory before opening the logger, and close it when finished.

import 'dart:io';
import 'package:logsmith/logsmith.dart';

Future<void> main() async {
  Directory('logs').createSync(recursive: true);

  final log = FileLogger(
    'logs/app.jsonl',
    rotation: FileRotation.size(maxBytes: 1024 * 1024, maxFiles: 5),
    flushOn: Level.error,
  );

  log.info('import started', attrs: {'job_id': 'job-18'});
  log.error('import failed', attrs: {'row': 27});
  await log.flush(); // Wait for a durability boundary.
  await log.close();
}

The default file format is compact JSON Lines. Other formats are explicit constructors, for example FileLogger.text('logs/app.log') or FileLogger.yaml('logs/events.yaml'). Calls to close() are idempotent; logging after close throws StateError.

Combining and adapting loggers

Use CompositeLogger to send the same event to multiple destinations. It forwards to children in order and closes lifecycle-aware children when closed.

final log = CompositeLogger([
  TerminalLogger.singleLine(name: 'checkout'),
  FileLogger('logs/checkout.jsonl', name: 'checkout'),
]);

log.withAttrs({'request_id': 'req-42'}).success(
  'payment captured',
  attrs: {'order_id': 'ord-7341'},
);

await log.close();

Other adapters cover common needs:

final quiet = SilentLogger(); // Accept and validate, but write nothing.
quiet.info('disabled by application configuration');

final async = AsyncLogger(FileLogger('logs/background.jsonl'));
async.info('accepted into the delivery queue');
await async.close(); // Drain, then close the inner logger.

final records = <Record>[];
final callback = CallbackLogger(records.add);
callback.warning('captured for application-specific handling');

CallbackLogger is a simple seam when application code needs the immutable Record. Extend the Logger base class only when the behavior itself must change.

Try the examples

The repository includes runnable examples for each logger and adapter. From the repository root:

dart pub get
dart run example/terminal_logger.dart
dart run example/machine_logger.dart
dart run example/file_logger.dart

Run the project checks with:

dart analyze
dart test

License

BSD 3-Clause. See LICENSE.

Libraries

logsmith
logsmith — use-case-oriented structured logging for Dart.
serialization
Advanced v2 record serialization utilities.