All 48 libraries

SugarLog

Colorful leveled logger

inspired by charmbracelet/log loggingclioutput

SugarLog code coverage

SugarLog is a leveled, colorful logger for PHP 8.3+ command-line tools. It writes Debug, Info, Warn, Error and Fatal records with structured key/value context, renders them as text, JSON or logfmt, and creates sub-loggers that carry persistent fields. The record model is inspired by charmbracelet/log (Go); the port is native PHP, not a binding.

Install

composer require sugarcraft/sugar-log

Requires PHP 8.3 or newer and psr/log ^3.0. The package requires its sugarcraft/ siblings at dev-master, so a project on the default stable minimum stability must add "minimum-stability": "dev" and "prefer-stable": true to its root composer.json.

Quickstart

use SugarCraft\Log\Logger;
use SugarCraft\Log\Level;

$log = Logger::new(level: Level::Debug);   // default threshold is Info; Debug opts in
$log->debug('preheat cycle', ['stage' => 1]);
$log->info('Starting oven', ['degree' => 375]);
$log->warn('Almost ready', ['batch' => 2]);
$log->error('Temperature too low', ['err' => 'underheated']);

$child = $log->with(['service' => 'bakery']);   // every line from $child carries service=bakery
$child->info('Batch complete');

All log levels + formats

Concepts and how it works

Levels. Level is an int-backed enum: Debug is -4, Info 0, Warn 4, Error 8 and Fatal 12. The values follow charmbracelet/log's deltas and are not RFC 5424 severities, so compare ->value when filtering. A record is emitted when its level value is at or above the logger's minimum level, which defaults to Info. print() and printf() bypass that filter.

Pipeline. Logger builds one record per call, hands it to a Formatter (TextFormatter unless you pass another), and writes the rendered line to the configured stream. Records at or above the error threshold go to the optional error stream instead. Fatal records are written first and then raise FatalLoggedException, a RuntimeException subclass.

Color is decided twice. The constructor consults the color-profile probe once, and a per-write gate (ColorGate::allowsColor()) keeps files and pipes free of ANSI bytes. Styles are snapshotted per logger, so changing one logger's styles does not recolor another.

Immutable children, mutable setters. with*() methods such as withPrefix() and with() return a new logger and leave the parent alone. set*() methods such as setPrefix() change the logger in place. The formatter and the minimum level have one spelling each, withFormatter() and withMinLevel().

Tasks and recipes

Write JSON lines to a file

use SugarCraft\Log\Logger;
use SugarCraft\Log\Formatter\JsonFormatter;

$file = fopen('/var/log/bakery.jsonl', 'a');
$log  = Logger::new(formatter: new JsonFormatter(), stream: $file);
$log->info('batch complete', ['loaves' => 12]);

A stream that is a file or a pipe receives plain bytes, so the JSON lines carry no escape sequences.

Route errors to stderr

use SugarCraft\Log\Logger;
use SugarCraft\Log\Level;

$log = Logger::new(errorStream: STDERR, errorStreamAt: Level::Error);
$log->info('still on stdout');
$log->error('goes to stderr');

Catch the fatal signal

use SugarCraft\Log\FatalLoggedException;
use SugarCraft\Log\Logger;

$log = Logger::new();
try {
    $log->fatal('out of flour');   // the record is written, then the exception is thrown
} catch (FatalLoggedException $e) {
    exit(1);
}

Forward PSR-3 calls and run hooks

use SugarCraft\Log\Logger;
use SugarCraft\Log\PsrBridge;
use SugarCraft\Log\Hook\HookRegistry;
use SugarCraft\Log\Level;

$hooks = new HookRegistry();
$hooks->onLevel(Level::Error, static function (Level $level, string $psr, string $msg, array $ctx): void {
    // page the on-call engineer, post to a chat channel, and so on
});

$psr = new PsrBridge(Logger::new(), $hooks);
$psr->error('oven door open', ['zone' => 2]);

Hooks fire only through PsrBridge or an explicit HookRegistry::fire(). Direct Logger calls never dispatch hooks.

Add caller location

use SugarCraft\Log\Logger;

$log = Logger::new(reportCaller: true);
$log->info('where am I');

The caller is the nearest frame outside the library, found by a bounded walk of at most 20 frames. When no such frame exists, the caller part is omitted rather than guessed.

API reference

ClassMemberPurpose
Loggernew(...)Build a logger. Named arguments: formatter, level, prefix, reportTimestamp, timeFormat, reportCaller, stream, partsOrder, errorStream, errorStreamAt.
Loggerdebug(), info(), warn(), error(), fatal()Level-bound methods taking (string $message, array $context = []).
Loggerdebugf() … fatalf(), printf()sprintf-style siblings. The level-bound helpers check enabled() before formatting.
Loggerlog(), print(), enabled(), flush()Explicit-level write, filter-bypassing write, threshold query, and stream flush.
Loggerwith(), withError(), withPrefix(), withFormatter(), withMinLevel(), withPartsOrder(), withTimeFormat(), withOutput(), withErrorStream()Return a child logger with one change applied.
LoggersetReportCaller(), setReportTimestamp(), setTimeFormat(), setPrefix(), setOutput(), setErrorStream(), setStyles(), setPartsOrder()Change the logger in place.
Loggerformatter(), level(), prefix(), output(), styles()Bare accessors for current state.
Loglogger(), setLogger(), reset()Process-shared facade over one lazily created default Logger.
Logdebug() … fatal(), print(), debugf() … fatalf()Static forms of the logger methods, forwarding to the default logger.
LoginstallPanicHandler(), removePanicHandler(), restoreTerminal()Uncaught-exception and fatal-error reporting, and terminal restoration.
LevelfromPsrString(), toPsrString(), label(), shortLabel()Map between the enum, PSR-3 strings and display labels. fromPsrString() returns null for an unknown string.
Formatterformat()Contract for renderers. Implemented by TextFormatter, JsonFormatter and LogfmtFormatter.
TextFormatter__construct(), withStyles(), withPartsOrder(), withReportTimestamp(), withTimeFormat(), withReportCaller(), withUseColors()Default human-readable renderer.
JsonFormatter__construct(bool $reportTimestamp, ?string $timeFormat)One JSON object per record.
LogfmtFormatter__construct(bool $reportTimestamp, ?string $timeFormat)One logfmt line per record.
Stylesshared(), snapshot(), copy(), keyStyle(), padLevelText()Public style slots: levels, keys, values, timestamp, prefix, caller, message, padLevelText.
PartsOrdernew(), syslog(), messageFirst(), has()Which record parts appear and in what order. The PART_* constants name them.
PsrBridge__construct(Logger $logger, ?HookRegistry $hooks)Implements Psr\Log\LoggerInterface. Its log() rejects an unknown level string with InvalidArgumentException.
Hook\HookRegistryonLevel(), addHook(), remove(), fire()Per-level callbacks, returning an id you can pass to remove().
Hook\HookonLevel()Interface for object hooks, registered with addHook().
StandardLogAdapterprint(), printLn(), fatal(), panic(), printf(), errorf(), fatalf(), panicf(), logger()Go-style call shape over a Logger. fatal() and panic() throw FatalLoggedException.
PanicFormatterpretty(), plain(), format(), withTitleStyle(), withExceptionStyle(), withBacktraceStyle(), withMutedStyle()Renders a crash report for a Throwable.
FatalLoggedException(class)Thrown after a Fatal record is written. It extends RuntimeException.
ColorGateallowsColor()Per-write decision for whether a destination gets ANSI bytes.
CallerFormatterfind()Finds the nearest caller outside the library, or null.
RecordKeysclaim(), isReserved()Namespaces context keys that collide with reserved record keys under the ctx_ prefix.
ValueCoercionstringify(), coerce()Turns arbitrary context values into printable text.
LogReadernew($path, $format, $partsOrder), tail($n, $filter), follow($cursor, $n, $filter, $limit), withPath(), withFormat(), withPartsOrder()Reads the last records of a JSON, logfmt or text log from its end, without loading the whole file.
LogFilternew(), withMinLevel(), withField(), matches(), apply()Keeps the LogRecords that meet a level threshold and field values.
LogViewernew($reader, $filter), init(), update(), view(), refresh(), tick(), withFilter(), withFollow(), withMaxRecords(), withHeight(), withWidth()A TEA model that shows filtered records and follows the file through Cmd ticks, appending every line written since the last read; f toggles follow.
LogRecordfield(), hasField()One parsed line: line, level, message, time, prefix, caller, fields.

Only methods declared in sugar-log/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Log

ByteWindow final readonly class

The byte-window mode of LogReader: a backward read of a growing window at the end of the file, LogReader::new($path)->tailWindow(200, ByteWindow::new()).

MethodSummary
static new(): selfA FIRST_BYTES window growing by GROWTH to WindowBoundary::LineStart.
withFirstBytes(int $bytes): selfThe bytes read from the end of the file before any growth.
withGrowth(int $factor): selfThe factor the window's length is multiplied by each time it misses its boundary. It must be at least 2, so the walk always makes progress.
withBoundary(WindowBoundary $boundary): selfThe rule the window grows until it meets.

CallerFormatter final class

Captures the file:line of the immediate caller outside the log package.

MethodSummary
static find(): ?stringWalk back the call stack to find the first file outside the log package.

FatalLoggedException final class

The exception Logger::fatal() throws once the Fatal record has landed on its stream.

Formatter interface

Log message formatter contract. Mirrors charmbracelet/log's Formatter interface.

MethodSummary
format(Level $level, string $message, array $context, \DateTimeImmutable $time, ?string $caller, ?string $prefix): stringFormat a log event into a string.

Lang final class

Per-library translation facade for sugar-log.

Level enum

Log level enum — mirrors charmbracelet/log levels.

Cases: Debug · Info · Warn · Error · Fatal

PHP also provides cases(), from() and tryFrom().

MethodSummary
static fromPsrString(string $psrLevel): ?selfMap a PSR-3 severity string onto the level ladder.
toPsrString(): stringThe canonical PSR-3 string for this level (inverse of the coarse fromPsrString() routing: Fatal → emergency, Info → info).
static fromLabel(string $label): ?selfParse a rendered level label back onto the ladder: the full label the JSON and logfmt formatters write (INFO) or the short one the text formatter writes (INF), in any case. Surrounding whitespace is ignored so a padded text label (INF ) still parses.
label(): string
shortLabel(): string

LineMode enum

How LogReader treats the bytes of each line before it parses one: LogReader::new($path)->withLineMode(LineMode::Raw).

Cases: Trimmed · Raw

PHP also provides cases(), from() and tryFrom().

Log final class

Static facade over a process-wide default Logger.

MethodSummary
static logger(): LoggerGet (or lazily create) the process-wide default logger.
static setLogger(Logger $logger): voidReplace the process-wide default logger.
static reset(): voidReset the default logger so the next call rebuilds it.
static debug(string $message, array $context = []): void
static info(string $message, array $context = []): void
static warn(string $message, array $context = []): void
static error(string $message, array $context = []): void
static fatal(string $message, array $context = []): void
static print(string $message, array $context = []): voidAlways print, ignoring level filters.
static debugf(string $format, mixed $context = [], mixed ...$args): voidFormatted proxies mirroring the Logger *f helpers — same sprintf semantics, same context-slot heuristic, same failure posture (fatalf writes the record, then throws RuntimeException).
static infof(string $format, mixed $context = [], mixed ...$args): void
static warnf(string $format, mixed $context = [], mixed ...$args): void
static errorf(string $format, mixed $context = [], mixed ...$args): void
static fatalf(string $format, mixed $context = [], mixed ...$args): void
static installPanicHandler(?PanicFormatter $formatter = null, bool $showLocals = false, array $redactPaths = []): voidInstall a panic handler that catches uncaught exceptions and renders them as a styled panic report.
static removePanicHandler(): voidUninstall the handler registered by self::installPanicHandler(), restoring the exception handling that existed before the FIRST install (PHP's builtin default when there was none). PHP cannot unregister the companion shutdown hook, so the install epoch is advanced and every registered hook self-retires. Idempotent: with nothing installed this is a no-op — it never pops a handler sugar-log does not own. self::reset() deliberately does NOT uninstall the panic handler; this method is its counterpart (install is process-lifetime state like setOutput, and must be undoable without one).
static restoreTerminal(bool $force = false): voidRestore the terminal to a usable state: exit altscreen and show cursor.

LogChunk final readonly class

What one LogReader::follow() read found.

MethodSummary
__construct(public array $records, public ?LogCursor $cursor, public bool $fresh)

LogCursor final readonly class

Where a LogReader::follow() read stopped: the byte just past the last complete line it took, in the file it took it from.

MethodSummary
__construct(public int $offset, public int $inode, public string $fingerprint)
equals(?self $other): boolTrue when $other points at the same byte of the same file.

LogFilter final readonly class

Which LogRecords to keep: LogFilter::new()->withMinLevel(Level::Warn) ->withField('svc', 'api')->apply($records).

MethodSummary
static new(): selfA filter that keeps every record.
withMinLevel(?Level $level): selfKeep records at $level or above; null drops the condition. A record whose level could not be read is not known to meet a threshold, so it is dropped while one is set.
withField(string $key, mixed $value): selfKeep records whose context entry $key equals $value. Calling it again for the same key replaces that condition.
matches(LogRecord $record): bool
apply(iterable $records): arrayThe records that match, in their original order.

LogFormat enum

The on-disk shape a LogReader parses, one per writing formatter.

Cases: Json · Logfmt · Text

PHP also provides cases(), from() and tryFrom().

LogReader final readonly class

Read side of a log file: LogReader::new($path, LogFormat::Json)->tail(50).

MethodSummary
static new(string $path, LogFormat $format = LogFormat::Text, ?PartsOrder $partsOrder = null): selfA reader over $path that parses lines as $format. $partsOrder is the writer's text layout (TextFormatter::withPartsOrder()); it only steers where a text line's level is looked for, and defaults to PartsOrder::new(), the layout a TextFormatter writes unless told otherwise.
withPath(string $path): self
withFormat(LogFormat $format): self
withPartsOrder(PartsOrder $partsOrder): selfThe PartsOrder the text lines were written with; JSON and logfmt ignore it.
withLineMode(LineMode $lineMode): selfHow each line's bytes are treated before it is parsed: LineMode::Trimmed (the default) or the raw-line mode, LineMode::Raw, which keeps the carriage return before the newline and counts whitespace-only lines as records.
tail(int $n, ?LogFilter $filter = null): arrayThe last $n records of the file, oldest first. With a $filter, the last $n records the filter keeps: the scan goes on back through the file until it has them, so matches far from the end are found too, at the cost of reading back to them.
tailWindow(int $n, ByteWindow $window): WindowTailThe byte-window mode: the last $n complete lines inside a backward window at the end of the file, oldest first, read as ByteWindow describes. tail() and follow() are untouched by it; this is a separate read.
follow(?LogCursor $from, int $n, ?LogFilter $filter = null, ?int $limit = null): LogChunkFollow the file from $from: the records written since that cursor, or, with no cursor or when the file was truncated or replaced since it was taken, the last $n records as tail() finds them ($fresh then says to replace rather than extend). Either way only records $filter keeps come back, and the returned cursor resumes the next read. A file truncated in place and regrown past the cursor before this read is caught by the cursor's fingerprint (LogCursor).

LogRecord final readonly class

One parsed log line, as LogReader hands it back.

MethodSummary
__construct(public string $line, public ?Level $level, public string $message, public ?string $time = null, public ?string $prefix = null, public ?string $caller = null, public array $fields = [])
hasField(string $key): boolTrue when the record carries a context entry named $key (even a null one).
field(string $key): mixedThe context entry named $key, or null when absent.

LogTailMsg final readonly class

The result of one LogViewer read, as the viewer's read Cmd found it when it ran: the records the filter keeps that were written since $from ($fresh false: the viewer appends them), or the file's last matching records ($fresh true: they replace what the viewer holds).

MethodSummary
__construct(public int $viewerId, public int $generation, public array $records, public ?string $error = null, public bool $chained = false, public ?LogCursor $from = null, public ?LogCursor $cursor = null, public bool $fresh = true)

LogTailWindow final readonly class

Raw line tail of a file through a fixed byte window: [$lines, $offset] = LogTailWindow::new($path)->lines(100).

MethodSummary
static new(string $path): selfA tail of $path through the default WINDOW_BYTES window.
withPath(string $path): self
withWindowBytes(int $bytes): selfThe most bytes lines() reads from the end of the file.
lines(int $n): arrayThe last $n lines inside the window, oldest first, and the byte offset the read stopped at (the file's size). $n = 0 answers no lines but still the offset.

LogTickMsg final readonly class

One beat of a LogViewer's follow chain: the LogViewer::tick() timer fired. It carries no records; the viewer decides on taking it whether to read, so the read always uses the viewer's current reader and follow setting instead of the ones the timer was armed with.

MethodSummary
__construct(public int $viewerId)

LogViewer final class

A TEA log viewer: the records of a log file a LogFilter keeps, following the file as it grows.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
static new(LogReader $reader, ?LogFilter $filter = null): selfA following viewer over $reader. With no $filter every record shows. Nothing is read until the Cmd from init() runs.
init(): ?\ClosureThe first read, whether or not the viewer follows (a viewer that never read has nothing to show), which also starts the follow chain.
update(Msg $msg): array
view(): stringThe filtered records that fit, one row each, exactly $height rows. Blank rows fill the space the records leave, after them: a view holding fewer records than its height shows them from the top row, so the newest sits on the bottom row only once the records fill the view.
subscriptions(): ?Subscriptions
refresh(): \ClosureA Cmd that reads now and hands the result back as a LogTailMsg, without waiting for the next tick: after withReader() or withFollow() it catches up at once instead of an interval later. It is a one-off read and never starts a second follow chain.
tick(): \ClosureA Cmd that hands back a LogTickMsg after $interval seconds: one beat of the follow chain init() starts. The viewer decides on taking the tick whether to read, so nothing is read here. The chain reschedules itself; issuing this yourself starts a second one.
visibleRecords(): arrayThe held records the filter keeps, oldest first — every record the viewer could show, before the height cut.
withReader(LogReader $reader): selfRead another file, from its tail. Reads of the old one in flight are dropped; a following viewer's chain reads the new one at its next tick, or issue refresh() to read it at once. A paused viewer reads nothing on a tick, so it keeps showing the old file's records until it resumes or a refresh() reads the new one.
withFilter(LogFilter $filter): selfKeep only the records $filter matches. The held records are narrowed at once; reads in flight are dropped, and the next read starts over from the tail through $filter, so a looser filter brings back the records the old one left out. A paused viewer reads nothing on a tick, so issue refresh() for that read while paused.
withFollow(bool $follow): selfFollow the file or freeze on what is held. A change drops the reads in flight, so a paused viewer takes no late read. The follow chain keeps running while paused without reading, so a resumed viewer reads again at the next tick; issue refresh() to read at once (the f key does). Setting the current value changes nothing.
withInterval(float $seconds): self
withTailSize(int $records): selfHow many matching records a read from the tail takes: the first read, and the one after a reader or filter change, a failed read or a truncated file. Later reads append every matching record written since, however many.
withMaxRecords(int $records): selfThe most records the viewer holds; past it the oldest are dropped.
withHeight(int $rows): self
withWidth(?int $columns): selfPad and clip every row to $columns cells; null renders rows at their own width. A clipped row ends in ….
withShowTimestamps(bool $show): selfShow a structured record's time as [time]. A text line shows as written either way.
withShowLevel(bool $show): selfShow a structured record's level as [INF]. A text line shows as written either way.
withScrollToBottom(bool $bottom): selfShow the newest records (true) or the oldest of those held (false) when they overflow the height.
withColor(bool $color): selfColor each row by its level; false renders plain text.
withStyles(Styles $styles): selfTake the level palette from $styles. The styles are read once here, so editing $styles afterwards does not reach this viewer.

Logger final class

Minimal colorful leveled logger. Mirrors charmbracelet/log's Logger API.

MethodSummary
__construct(?Formatter $formatter = null, ?Level $level = null, ?string $prefix = null, bool $reportTimestamp = true, ?string $timeFormat = null, bool $reportCaller = false, mixed $stream = null, ?PartsOrder $partsOrder = null, mixed $errorStream = null, ?Level $errorStreamAt = null)
static new(mixed ...$args): selfNamed-argument constructor — charm's option funcs rendered with PHP's named args: Logger::new(prefix: 'svc', level: Level::Warn).
log(Level $level, string $message, array $context = []): void
print(string $message, array $context = []): voidUnlike the level methods, this bypasses the minimum-level filter — but it does not print bare: the Info level label still renders.
flush(): voidPush buffered bytes out to both destinations.
debug(string $message, array $context = []): void
info(string $message, array $context = []): void
warn(string $message, array $context = []): void
error(string $message, array $context = []): void
fatal(string $message, array $context = []): void
enabled(Level $level): boolWhether a message at $level would be emitted under the current minLevel.
debugf(string $format, mixed $context = [], mixed ...$args): void
infof(string $format, mixed $context = [], mixed ...$args): void
warnf(string $format, mixed $context = [], mixed ...$args): void
errorf(string $format, mixed $context = [], mixed ...$args): void
fatalf(string $format, mixed $context = [], mixed ...$args): void
printf(string $format, mixed $context = [], mixed ...$args): void
with(array $fields): selfCreate a child logger with additional persistent fields.
withError(string|\Throwable $err): selfCreate a child logger carrying $err under the house-named err field (parity with charm's WithError).
withPrefix(string $prefix): self
withFormatter(Formatter $formatter): selfChild logger rendering through $formatter (a plain TextFormatter is re-seeded with this logger's presentation knobs, see the adopt seam).
withMinLevel(Level $level): selfChild logger whose threshold is $level.
withPartsOrder(PartsOrder $partsOrder): self
setReportCaller(bool $on): void
setReportTimestamp(bool $on): void
setTimeFormat(?string $timeFormat): voidChange the timestamp format in place (parity with charm's SetTimeFormat).
withTimeFormat(?string $timeFormat): selfClone-with-time-format twin of setTimeFormat().
setPrefix(?string $prefix): void
setOutput(mixed $stream): voidSet the main output stream in-place (the error stream, if any, is kept).
withOutput(mixed $stream): selfCreate a child logger with a different main output stream.
setErrorStream(mixed $stream, ?Level $errorStreamAt = null): voidInstall (or replace) the secondary error stream in-place.
withErrorStream(mixed $stream, ?Level $errorStreamAt = null): selfCreate a child logger routing severe records to a second stream.
styles(): StylesStyles object for text-formatter styling.
formatter(): FormatterThe formatter currently rendering records. A bare TextFormatter handed to the constructor or withFormatter() comes back re-seeded with this logger's caller/timestamp/time-format state (SL-14 adopt seam), so the returned object is the one actually on the write path.
level(): LevelMinimum level this logger writes. Named for the constructor parameter (level:), not withMinLevel() — the ctor noun is the source of truth.
prefix(): ?stringPrefix string, or null when none is set.
output(): mixedMain output stream (mixed: resource or sink accepted by the ctor). Errors at/above the setErrorStream() threshold go to that secondary stream instead; this accessor returns the primary one.
setStyles(Styles $styles): void
setPartsOrder(PartsOrder $partsOrder): void

PanicFormatter final class

Formats an uncaught exception into a human-readable panic report.

MethodSummary
static pretty(bool $showLocals = false, array $redactPaths = []): selfDefault pretty formatter with color-coded output.
static plain(bool $showLocals = false, array $redactPaths = []): selfPlain formatter for non-TTY environments (e.g. files / CI).
withTitleStyle(Style $style): selfReplace the style of the PANIC banner label.
withExceptionStyle(Style $style): selfReplace the style of the exception class name and message rows.
withBacktraceStyle(Style $style): selfReplace the style of the primary file header and the frame rows.
withMutedStyle(Style $style): selfReplace the style of the footer, collapsed-frame counters and locals.
format(\Throwable $e): stringFormat an exception into a panic report string.

PartsOrder final class

Config DTO for configurable timestamp/level/prefix/caller/message/fields ordering in formatters.

MethodSummary
__construct(?array $parts = null)
static new(): selfDefaultPartsOrder: timestamp level prefix caller message fields.
static syslog(): selfSyslogOrder: timestamp level message fields (no prefix/caller).
static messageFirst(): selfMessageFirstOrder: message level timestamp fields (prefix/caller omitted).
has(string $part): bool

PsrBridge final class

PSR-3 bridge wrapping a Logger instance.

MethodSummary
__construct(Logger $logger, ?HookRegistry $hooks = null)
emergency(string|\Stringable $message, array $context = []): void
alert(string|\Stringable $message, array $context = []): void
critical(string|\Stringable $message, array $context = []): void
error(string|\Stringable $message, array $context = []): void
warning(string|\Stringable $message, array $context = []): void
notice(string|\Stringable $message, array $context = []): void
info(string|\Stringable $message, array $context = []): void
debug(string|\Stringable $message, array $context = []): void
log(mixed $level, string|\Stringable $message, array $context = []): voidPSR-3 generic entry. The interface leaves $level untyped; only the eight PSR-3 level strings (as string or Stringable) resolve. Anything else — an unknown string, a number, null, an array — is a caller error and raises InvalidArgumentException as PSR-3 sanctions, instead of silently mislabeling the record as Info.

StandardLogAdapter final class

Go-style stdlog call pattern (Print/Printf/Println/Fatal/Fatalf/Panic/ Panicf, plus an Errorf twin of Logger::errorf() that Go's stdlib never had) over a sugar-log Logger.

MethodSummary
__construct(Logger $logger, ?Level $forceLevel = null)
logger(): Logger
print(mixed ...$args): voidPrint a line — unconditionally when no level was forced.
printLn(mixed ...$args): void
fatal(mixed ...$args): voidWrite an FTL record, then throw.
panic(mixed ...$args): voidAlias of self::fatal() — the name kept for Go-shaped call sites.
printf(string $format, mixed ...$args): voidFormatted self::print() — Go stdlog Printf parity.
errorf(string $format, mixed ...$args): voidFormatted Error record — the adapter twin of Logger::errorf().
fatalf(string $format, mixed ...$args): voidFormatted self::fatal() — Go stdlog Fatalf parity.
panicf(string $format, mixed ...$args): voidFormatted self::panic() — Go stdlog Panicf parity.

Styles final class

Styles for log level rendering in text output.

MethodSummary
__construct()
static shared(): selfThe process-wide shared Styles instance, now OPT-IN: Loggers and TextFormatters built without styles land on an independent self::snapshot() ([SL-35]), so this singleton only couples the callers that hand it over explicitly (new TextFormatter(styles: Styles::shared())).
static snapshot(): selfAn INDEPENDENT copy of the shared defaults.
copy(): selfCopy of this instance (fresh arrays, same Style objects).
static padLevelText(string $label): stringPad a level label to a fixed width for visual alignment. Mirrors charmbracelet/log's padLevelText.
keyStyle(string $field): StyleGet style for a specific field key.

WindowBoundary enum

Where a ByteWindow stops growing: the boundary rule of the byte-window mode, LogReader::tailWindow($n, ByteWindow::new()).

Cases: LineStart

PHP also provides cases(), from() and tryFrom().

WindowTail final readonly class

What one byte-window read (LogReader::tailWindow()) found.

MethodSummary
__construct(public array $records, public int $start)
cut(): boolWhether the window was cut: the file holds bytes before $start that this read did not take. When it was not cut and fewer records came back than asked for, the whole file was read and any older lines can only be in another file (a rotated generation, say).

SugarCraft\Log\Formatter

JsonFormatter final class

JSON formatter — emits one JSON object per log line. Mirrors charmbracelet/log's JSONFormatter.

MethodSummary
__construct(bool $reportTimestamp = true, ?string $timeFormat = null)
format(Level $level, string $message, array $context, \DateTimeImmutable $time, ?string $caller, ?string $prefix): string

LogfmtFormatter final class

Logfmt formatter — emits key=value pairs on a single line. Mirrors charmbracelet/log's LogfmtFormatter.

MethodSummary
__construct(bool $reportTimestamp = true, ?string $timeFormat = null)
format(Level $level, string $message, array $context, \DateTimeImmutable $time, ?string $caller, ?string $prefix): string

RecordKeys final class

Record-key policy shared by the machine-readable formatters.

MethodSummary
static claim(string $key, array &$used): stringReturn a collision-free key for the record, registering it in $used.
static isReserved(string $key): boolTrue when $key names an envelope field that context must not overwrite.

TextFormatter final class

Human-readable text formatter with optional color styling. Mirrors charmbracelet/log's TextFormatter.

MethodSummary
__construct(bool $reportTimestamp = true, ?string $timeFormat = null, bool $reportCaller = false, ?bool $useColors = null, ?Styles $styles = null, ?PartsOrder $partsOrder = null)
format(Level $level, string $message, array $context, \DateTimeImmutable $time, ?string $caller, ?string $prefix): string
withStyles(Styles $styles): selfCreate a new TextFormatter with different styles, preserving all other settings.
withPartsOrder(PartsOrder $partsOrder): selfCreate a new TextFormatter with different parts order, preserving all other settings.
withReportTimestamp(bool $reportTimestamp): selfCreate a new TextFormatter with the timestamp part switched, preserving all other settings. Used by the Logger formatter-adopt seam [PHP-02].
withTimeFormat(?string $timeFormat): selfCreate a new TextFormatter with a different time format, preserving all other settings. Used by the Logger formatter-adopt seam [PHP-02].
withReportCaller(bool $reportCaller): selfCreate a new TextFormatter with the caller part switched, preserving all other settings. Used by the Logger formatter-adopt seam [PHP-02].
withUseColors(bool $useColors): selfCreate a new TextFormatter with coloring switched, preserving all other settings. Used by \SugarCraft\Log\Logger's destination gate to deliver a plain mirror of the configured formatter when the target stream cannot render ANSI (C2).

ValueCoercion final class

Safe value stringification for log formatters.

MethodSummary
static stringify(mixed $v, int $depth = 0, string $delim = ' '): stringConvert a value to a string representation.
static coerce(mixed $v, int $depth = 0): mixedCoerce a value for JSON encoding in JsonFormatter.

SugarCraft\Log\Hook

Hook interface

Log hook contract — invoked when a log entry is emitted.

MethodSummary
onLevel(Level $level, string $psrLevel, string $message, array $context): voidCalled when a log event fires at the given level.

HookRegistry final class

Registry for log hooks — collects callbacks per level and fires them when a matching log entry is emitted.

MethodSummary
onLevel(Level $level, callable $callback): intRegister a callback to be invoked for all events at or above $level.
addHook(Level $level, Hook $hook): intRegister a Hook object to be invoked for all events at or above $level.
remove(int $id): voidRemove a registered handler by its ID.
fire(Level $level, string $psrLevel, string $message, array $context): voidFire all registered handlers whose level matches the given $level.

SugarCraft\Log\Support

Stdio final class

SAPI-safe access to the process STDIO channels.

MethodSummary
static out()
static err()

Configuration and options

Every option is a named argument of Logger::new(). The same values can be changed later with the matching set*() or with*() method.

OptionTypeDefaultEffect
formatter?FormatterTextFormatterRenders each record.
level?LevelLevel::InfoMinimum level that is emitted. Lower records are dropped unless written with print().
prefix?stringnullText placed before each message.
reportTimestampbooltrueInclude a timestamp in each record.
timeFormat?stringnull, meaning Y/m/d H:i:sPHP date format for the timestamp.
reportCallerboolfalseInclude the basename:line of the nearest caller.
streammixedSTDOUTResource or openable path that receives records.
partsOrder?PartsOrderPartsOrder::new()Which parts appear, and in what order.
errorStreammixednullOptional second stream for severe records.
errorStreamAt?LevelLevel::ErrorThreshold at which records go to errorStream.

An invalid stream throws InvalidArgumentException at construction.

Styling and theming

Each logger owns a Styles instance. Its public arrays levels, keys and values map a level, a generic key role, or an individual field name to a style, and its timestamp, prefix, caller and message properties style the other parts. Set padLevelText to true to pad level labels to a common width. Use keyStyle() to read the style for one field.

use SugarCraft\Log\Logger;
use SugarCraft\Log\Styles;

$styles = Styles::snapshot();   // an independent copy; shared() is the shared instance
$styles->padLevelText = true;
$log = Logger::new();
$log->setStyles($styles);

Color is chosen at construction by the color-profile probe, where NO_COLOR is honored. CLICOLOR_FORCE and FORCE_COLOR outrank NO_COLOR there. A non-terminal destination still receives plain bytes on every write, and CLICOLOR_FORCE reaches that per-write gate when it is set to any non-empty value other than 0.

Examples

  • examples/demo.php runs every level, the structured fields, sub-loggers, the JSON and logfmt formatters, and the stdlog adapter in one run.
  • examples/panic-handler.php installs Log::installPanicHandler() and then triggers a fatal error so the styled panic report is visible.
  • examples/panic-restore.php restores the terminal after raw mode was entered outside the normal program loop. It uses Tty from sugarcraft/sugar-core, which the package already requires.

Run any of them from the package root with php examples/demo.php.

Testing

Run the suite from the package root with vendor/bin/phpunit. The tests cover the logger, each formatter, the record-integrity rules, the PSR-3 bridge, the hook registry, the stdlog adapter, the panic formatter and the locale catalogs. ReadmeSnippetsTest lints and runs every fenced PHP block in the README, so a documented snippet that drifts from the API fails the suite.

Troubleshooting and FAQ

Debug lines never appear

The default threshold is Level::Info. Pass level: Level::Debug to Logger::new(), or derive a child with withMinLevel(Level::Debug). The shared logger behind the Log facade is changed with Log::setLogger(Log::logger()->withMinLevel(Level::Debug)).

Colors appear in a log file, or never appear in a terminal

Files and pipes receive plain bytes by design. The per-write gate turns color on for a non-terminal destination only when CLICOLOR_FORCE is set to any non-empty value other than 0, such as 1 or true. NO_COLOR is read once, when the logger is constructed. Exporting it later does not change a logger that already exists.

Hooks never run for a direct logger call

HookRegistry callbacks are dispatched only by PsrBridge or by an explicit fire(). Log through a PsrBridge built with the registry, or call fire() yourself.

A script stops after fatal()

This is intended. The record is written first, then FatalLoggedException is thrown. Catch it at the entry point, as in the fatal recipe above, if the script should exit cleanly with a status code.

A context field is written as ctx_something

The record keys level, msg, time, caller, prefix and _encode_error are reserved. A context field that uses one of those names, or a name already claimed earlier in the same record, is written with a ctx_ prefix so it cannot overwrite the record's own parts. Rename the field to avoid the prefix.

reportCaller shows no file and line

Caller detection is best effort. It walks at most 20 frames and omits the caller part when no frame outside the library is found within that bound.

Upstream mapping

charmbracelet/log (Go)SugarLog (PHP)Notes
Logger and level functionsLogger, Log, LevelLevel deltas match upstream; the methods are PHP-shaped.
Formatter interfaceFormatter, TextFormatter, JsonFormatter, LogfmtFormatterDocblocks cite the upstream interface.
Caller reportingCallerFormatter, reportCallerBounded frame walk instead of the Go runtime call.
StylesStylesMirrors the shape (levels keyed by level, per-field overrides), not the Go type.
Standard library log call patternStandardLogAdapterA shape, not an interface. For PSR-3 use PsrBridge.

For where SugarLog sits among the other ports, see the project map in docs/MATCHUPS.md.

Changelog and versioning

The package ships no separate changelog file. It is published from the monorepo with the other sugarcraft/* packages on dev-master, so the git history of the sugar-log/ directory is the release record. The stability note under Install explains the dev-master requirement.

Source on GitHub →