SugarLog
Colorful leveled logger
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');

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
| Class | Member | Purpose |
|---|---|---|
Logger | new(...) | Build a logger. Named arguments: formatter, level, prefix, reportTimestamp, timeFormat, reportCaller, stream, partsOrder, errorStream, errorStreamAt. |
Logger | debug(), info(), warn(), error(), fatal() | Level-bound methods taking (string $message, array $context = []). |
Logger | debugf() … fatalf(), printf() | sprintf-style siblings. The level-bound helpers check enabled() before formatting. |
Logger | log(), print(), enabled(), flush() | Explicit-level write, filter-bypassing write, threshold query, and stream flush. |
Logger | with(), withError(), withPrefix(), withFormatter(), withMinLevel(), withPartsOrder(), withTimeFormat(), withOutput(), withErrorStream() | Return a child logger with one change applied. |
Logger | setReportCaller(), setReportTimestamp(), setTimeFormat(), setPrefix(), setOutput(), setErrorStream(), setStyles(), setPartsOrder() | Change the logger in place. |
Logger | formatter(), level(), prefix(), output(), styles() | Bare accessors for current state. |
Log | logger(), setLogger(), reset() | Process-shared facade over one lazily created default Logger. |
Log | debug() … fatal(), print(), debugf() … fatalf() | Static forms of the logger methods, forwarding to the default logger. |
Log | installPanicHandler(), removePanicHandler(), restoreTerminal() | Uncaught-exception and fatal-error reporting, and terminal restoration. |
Level | fromPsrString(), toPsrString(), label(), shortLabel() | Map between the enum, PSR-3 strings and display labels. fromPsrString() returns null for an unknown string. |
Formatter | format() | 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. |
Styles | shared(), snapshot(), copy(), keyStyle(), padLevelText() | Public style slots: levels, keys, values, timestamp, prefix, caller, message, padLevelText. |
PartsOrder | new(), 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\HookRegistry | onLevel(), addHook(), remove(), fire() | Per-level callbacks, returning an id you can pass to remove(). |
Hook\Hook | onLevel() | Interface for object hooks, registered with addHook(). |
StandardLogAdapter | print(), printLn(), fatal(), panic(), printf(), errorf(), fatalf(), panicf(), logger() | Go-style call shape over a Logger. fatal() and panic() throw FatalLoggedException. |
PanicFormatter | pretty(), 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. |
ColorGate | allowsColor() | Per-write decision for whether a destination gets ANSI bytes. |
CallerFormatter | find() | Finds the nearest caller outside the library, or null. |
RecordKeys | claim(), isReserved() | Namespaces context keys that collide with reserved record keys under the ctx_ prefix. |
ValueCoercion | stringify(), coerce() | Turns arbitrary context values into printable text. |
LogReader | new($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. |
LogFilter | new(), withMinLevel(), withField(), matches(), apply() | Keeps the LogRecords that meet a level threshold and field values. |
LogViewer | new($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. |
LogRecord | field(), 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()).
| Method | Summary |
|---|---|
static new(): self | A FIRST_BYTES window growing by GROWTH to WindowBoundary::LineStart. |
withFirstBytes(int $bytes): self | The bytes read from the end of the file before any growth. |
withGrowth(int $factor): self | The 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): self | The rule the window grows until it meets. |
CallerFormatter final class
Captures the file:line of the immediate caller outside the log package.
| Method | Summary |
|---|---|
static find(): ?string | Walk 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.
| Method | Summary |
|---|---|
format(Level $level, string $message, array $context, \DateTimeImmutable $time, ?string $caller, ?string $prefix): string | Format 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().
| Method | Summary |
|---|---|
static fromPsrString(string $psrLevel): ?self | Map a PSR-3 severity string onto the level ladder. |
toPsrString(): string | The canonical PSR-3 string for this level (inverse of the coarse fromPsrString() routing: Fatal → emergency, Info → info). |
static fromLabel(string $label): ?self | Parse 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.
| Method | Summary |
|---|---|
static logger(): Logger | Get (or lazily create) the process-wide default logger. |
static setLogger(Logger $logger): void | Replace the process-wide default logger. |
static reset(): void | Reset 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 = []): void | Always print, ignoring level filters. |
static debugf(string $format, mixed $context = [], mixed ...$args): void | Formatted 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 = []): void | Install a panic handler that catches uncaught exceptions and renders them as a styled panic report. |
static removePanicHandler(): void | Uninstall 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): void | Restore the terminal to a usable state: exit altscreen and show cursor. |
LogChunk final readonly class
What one LogReader::follow() read found.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__construct(public int $offset, public int $inode, public string $fingerprint) | |
equals(?self $other): bool | True 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).
| Method | Summary |
|---|---|
static new(): self | A filter that keeps every record. |
withMinLevel(?Level $level): self | Keep 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): self | Keep records whose context entry $key equals $value. Calling it again for the same key replaces that condition. |
matches(LogRecord $record): bool | |
apply(iterable $records): array | The 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).
| Method | Summary |
|---|---|
static new(string $path, LogFormat $format = LogFormat::Text, ?PartsOrder $partsOrder = null): self | A 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): self | The PartsOrder the text lines were written with; JSON and logfmt ignore it. |
withLineMode(LineMode $lineMode): self | How 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): array | The 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): WindowTail | The 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): LogChunk | Follow 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.
| Method | Summary |
|---|---|
__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): bool | True when the record carries a context entry named $key (even a null one). |
field(string $key): mixed | The 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).
| Method | Summary |
|---|---|
__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).
| Method | Summary |
|---|---|
static new(string $path): self | A tail of $path through the default WINDOW_BYTES window. |
withPath(string $path): self | |
withWindowBytes(int $bytes): self | The most bytes lines() reads from the end of the file. |
lines(int $n): array | The 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.
| Method | Summary |
|---|---|
__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/.
| Method | Summary |
|---|---|
static new(LogReader $reader, ?LogFilter $filter = null): self | A following viewer over $reader. With no $filter every record shows. Nothing is read until the Cmd from init() runs. |
init(): ?\Closure | The 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(): string | The 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(): \Closure | A 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(): \Closure | A 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(): array | The held records the filter keeps, oldest first — every record the viewer could show, before the height cut. |
withReader(LogReader $reader): self | Read 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): self | Keep 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): self | Follow 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): self | How 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): self | The most records the viewer holds; past it the oldest are dropped. |
withHeight(int $rows): self | |
withWidth(?int $columns): self | Pad and clip every row to $columns cells; null renders rows at their own width. A clipped row ends in …. |
withShowTimestamps(bool $show): self | Show a structured record's time as [time]. A text line shows as written either way. |
withShowLevel(bool $show): self | Show a structured record's level as [INF]. A text line shows as written either way. |
withScrollToBottom(bool $bottom): self | Show the newest records (true) or the oldest of those held (false) when they overflow the height. |
withColor(bool $color): self | Color each row by its level; false renders plain text. |
withStyles(Styles $styles): self | Take 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.
| Method | Summary |
|---|---|
__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): self | Named-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 = []): void | Unlike the level methods, this bypasses the minimum-level filter — but it does not print bare: the Info level label still renders. |
flush(): void | Push 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): bool | Whether 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): self | Create a child logger with additional persistent fields. |
withError(string|\Throwable $err): self | Create a child logger carrying $err under the house-named err field (parity with charm's WithError). |
withPrefix(string $prefix): self | |
withFormatter(Formatter $formatter): self | Child logger rendering through $formatter (a plain TextFormatter is re-seeded with this logger's presentation knobs, see the adopt seam). |
withMinLevel(Level $level): self | Child logger whose threshold is $level. |
withPartsOrder(PartsOrder $partsOrder): self | |
setReportCaller(bool $on): void | |
setReportTimestamp(bool $on): void | |
setTimeFormat(?string $timeFormat): void | Change the timestamp format in place (parity with charm's SetTimeFormat). |
withTimeFormat(?string $timeFormat): self | Clone-with-time-format twin of setTimeFormat(). |
setPrefix(?string $prefix): void | |
setOutput(mixed $stream): void | Set the main output stream in-place (the error stream, if any, is kept). |
withOutput(mixed $stream): self | Create a child logger with a different main output stream. |
setErrorStream(mixed $stream, ?Level $errorStreamAt = null): void | Install (or replace) the secondary error stream in-place. |
withErrorStream(mixed $stream, ?Level $errorStreamAt = null): self | Create a child logger routing severe records to a second stream. |
styles(): Styles | Styles object for text-formatter styling. |
formatter(): Formatter | The 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(): Level | Minimum level this logger writes. Named for the constructor parameter (level:), not withMinLevel() — the ctor noun is the source of truth. |
prefix(): ?string | Prefix string, or null when none is set. |
output(): mixed | Main 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.
| Method | Summary |
|---|---|
static pretty(bool $showLocals = false, array $redactPaths = []): self | Default pretty formatter with color-coded output. |
static plain(bool $showLocals = false, array $redactPaths = []): self | Plain formatter for non-TTY environments (e.g. files / CI). |
withTitleStyle(Style $style): self | Replace the style of the PANIC banner label. |
withExceptionStyle(Style $style): self | Replace the style of the exception class name and message rows. |
withBacktraceStyle(Style $style): self | Replace the style of the primary file header and the frame rows. |
withMutedStyle(Style $style): self | Replace the style of the footer, collapsed-frame counters and locals. |
format(\Throwable $e): string | Format an exception into a panic report string. |
PartsOrder final class
Config DTO for configurable timestamp/level/prefix/caller/message/fields ordering in formatters.
| Method | Summary |
|---|---|
__construct(?array $parts = null) | |
static new(): self | DefaultPartsOrder: timestamp level prefix caller message fields. |
static syslog(): self | SyslogOrder: timestamp level message fields (no prefix/caller). |
static messageFirst(): self | MessageFirstOrder: message level timestamp fields (prefix/caller omitted). |
has(string $part): bool |
PsrBridge final class
PSR-3 bridge wrapping a Logger instance.
| Method | Summary |
|---|---|
__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 = []): void | PSR-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.
| Method | Summary |
|---|---|
__construct(Logger $logger, ?Level $forceLevel = null) | |
logger(): Logger | |
print(mixed ...$args): void | Print a line — unconditionally when no level was forced. |
printLn(mixed ...$args): void | |
fatal(mixed ...$args): void | Write an FTL record, then throw. |
panic(mixed ...$args): void | Alias of self::fatal() — the name kept for Go-shaped call sites. |
printf(string $format, mixed ...$args): void | Formatted self::print() — Go stdlog Printf parity. |
errorf(string $format, mixed ...$args): void | Formatted Error record — the adapter twin of Logger::errorf(). |
fatalf(string $format, mixed ...$args): void | Formatted self::fatal() — Go stdlog Fatalf parity. |
panicf(string $format, mixed ...$args): void | Formatted self::panic() — Go stdlog Panicf parity. |
Styles final class
Styles for log level rendering in text output.
| Method | Summary |
|---|---|
__construct() | |
static shared(): self | The 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(): self | An INDEPENDENT copy of the shared defaults. |
copy(): self | Copy of this instance (fresh arrays, same Style objects). |
static padLevelText(string $label): string | Pad a level label to a fixed width for visual alignment. Mirrors charmbracelet/log's padLevelText. |
keyStyle(string $field): Style | Get 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.
| Method | Summary |
|---|---|
__construct(public array $records, public int $start) | |
cut(): bool | Whether 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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
static claim(string $key, array &$used): string | Return a collision-free key for the record, registering it in $used. |
static isReserved(string $key): bool | True 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.
| Method | Summary |
|---|---|
__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): self | Create a new TextFormatter with different styles, preserving all other settings. |
withPartsOrder(PartsOrder $partsOrder): self | Create a new TextFormatter with different parts order, preserving all other settings. |
withReportTimestamp(bool $reportTimestamp): self | Create a new TextFormatter with the timestamp part switched, preserving all other settings. Used by the Logger formatter-adopt seam [PHP-02]. |
withTimeFormat(?string $timeFormat): self | Create a new TextFormatter with a different time format, preserving all other settings. Used by the Logger formatter-adopt seam [PHP-02]. |
withReportCaller(bool $reportCaller): self | Create a new TextFormatter with the caller part switched, preserving all other settings. Used by the Logger formatter-adopt seam [PHP-02]. |
withUseColors(bool $useColors): self | Create 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.
| Method | Summary |
|---|---|
static stringify(mixed $v, int $depth = 0, string $delim = ' '): string | Convert a value to a string representation. |
static coerce(mixed $v, int $depth = 0): mixed | Coerce a value for JSON encoding in JsonFormatter. |
SugarCraft\Log\Hook
Hook interface
Log hook contract — invoked when a log entry is emitted.
| Method | Summary |
|---|---|
onLevel(Level $level, string $psrLevel, string $message, array $context): void | Called 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.
| Method | Summary |
|---|---|
onLevel(Level $level, callable $callback): int | Register a callback to be invoked for all events at or above $level. |
addHook(Level $level, Hook $hook): int | Register a Hook object to be invoked for all events at or above $level. |
remove(int $id): void | Remove a registered handler by its ID. |
fire(Level $level, string $psrLevel, string $message, array $context): void | Fire all registered handlers whose level matches the given $level. |
SugarCraft\Log\Support
Stdio final class
SAPI-safe access to the process STDIO channels.
| Method | Summary |
|---|---|
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.
| Option | Type | Default | Effect |
|---|---|---|---|
formatter | ?Formatter | TextFormatter | Renders each record. |
level | ?Level | Level::Info | Minimum level that is emitted. Lower records are dropped unless written with print(). |
prefix | ?string | null | Text placed before each message. |
reportTimestamp | bool | true | Include a timestamp in each record. |
timeFormat | ?string | null, meaning Y/m/d H:i:s | PHP date format for the timestamp. |
reportCaller | bool | false | Include the basename:line of the nearest caller. |
stream | mixed | STDOUT | Resource or openable path that receives records. |
partsOrder | ?PartsOrder | PartsOrder::new() | Which parts appear, and in what order. |
errorStream | mixed | null | Optional second stream for severe records. |
errorStreamAt | ?Level | Level::Error | Threshold 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.phpruns every level, the structured fields, sub-loggers, the JSON and logfmt formatters, and the stdlog adapter in one run.examples/panic-handler.phpinstallsLog::installPanicHandler()and then triggers a fatal error so the styled panic report is visible.examples/panic-restore.phprestores the terminal after raw mode was entered outside the normal program loop. It usesTtyfromsugarcraft/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 functions | Logger, Log, Level | Level deltas match upstream; the methods are PHP-shaped. |
| Formatter interface | Formatter, TextFormatter, JsonFormatter, LogfmtFormatter | Docblocks cite the upstream interface. |
| Caller reporting | CallerFormatter, reportCaller | Bounded frame walk instead of the Go runtime call. |
| Styles | Styles | Mirrors the shape (levels keyed by level, per-field overrides), not the Go type. |
| Standard library log call pattern | StandardLogAdapter | A 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.