All 42 libraries

SugarLog

Colorful leveled logger

inspired by charmbracelet/log loggingclioutput

SugarLog code coverage

Minimal, colorful leveled logging. Debug / Info / Warn / Error / Fatal with structured key/value context, Text / JSON / Logfmt formatters, and sub-loggers with persistent fields.

Install

composer require sugarcraft/sugar-log

Quickstart

use SugarCraft\Log\Logger;

$log = Logger::new();
$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');

What's in the box

Leveled loggingDebug, Info, Warn, Error, Fatal. Color runs in two layers: a construction-time style profile that honors NO_COLOR / CLICOLOR_FORCE, and a per-write gate that downgrades non-TTY destinations so files and pipes get plain bytes.
Three formattersTextFormatter (default), JsonFormatter, LogfmtFormatter — swap via withFormatter().
Structured contextArbitrary key/value pairs attached to every log call.
Sub-loggerswith(array $fields) creates a child logger that inherits all context.
StandardLogAdapterGo-style print()/printLn()/fatal()/panic() call pattern over a sugar-log Logger — a shape, not an interface (implements no contract); for PSR-3 interoperability use PsrBridge.
PSR-3 bridgePsrBridge wraps a Logger and exposes the full PSR-3 LoggerInterface API.
Hook systemRegister per-level callbacks via HookRegistry::onLevel() for middleware-style interceptors — dispatched only by PsrBridge (or an explicit fire()); direct Logger calls never fire hooks.
Caller inforeportCaller on Logger adds basename:line of the nearest caller outside the library — best-effort: a bounded 20-frame walk, and the part is omitted when no such caller is found.
PartsOrder DTOConfigure which log-parts appear and in what order — default, syslog, or custom.

Source & demos

Try the quickstart →

API

ClassMethodDescription
Loggernew()Create a new logger
Loggerdebug(msg, context)Log debug message
Loggerinfo(msg, context)Log info message
Loggerwarn(msg, context)Log warning message
Loggererror(msg, context)Log error message
Loggerfatal(msg, context)Log fatal message
Loggerdebugf/infof/warnf/errorf/fatalf(format, context, args)sprintf siblings per level — slot two is mixed (array = context, scalar = first argument); enabled() guards the formatting
Loggerprintf(format, context, args)sprintf sibling of print() — bypasses the level filter
Loggerenabled(Level)Whether a level passes the current minLevel
Loggerwith(array)Create child logger with persistent context
LoggerwithFormatter(Formatter)Set output formatter
LoggerwithMinLevel(Level)Set minimum output level
LoggerwithPrefix(string)Set per-line prefix
LoggersetReportCaller(bool)Enable/disable caller basename:line reporting (best-effort 20-frame walk)
LoggersetReportTimestamp(bool)Enable/disable timestamp
Loggerstyles()Get Styles object for level/field styling
Loggerstyles()->keys[name]Per-field ANSI style override (time, level, prefix, caller, message, key, value)
PsrBridgenew(Logger, ?HookRegistry)Wrap a Logger with full PSR-3 API
PsrBridgeemergency(msg, ctx)PSR-3 emergency — maps to Level::Fatal
PsrBridgealert(msg, ctx)PSR-3 alert — maps to Level::Fatal
PsrBridgecritical(msg, ctx)PSR-3 critical — maps to Level::Fatal
PsrBridgeerror(msg, ctx)PSR-3 error — maps to Level::Error
PsrBridgewarning(msg, ctx)PSR-3 warning — maps to Level::Warn
PsrBridgenotice(msg, ctx)PSR-3 notice — maps to Level::Info
PsrBridgeinfo(msg, ctx)PSR-3 info — maps to Level::Info
PsrBridgedebug(msg, ctx)PSR-3 debug — maps to Level::Debug
PsrBridgelog(level, msg, ctx)Generic PSR-3 log dispatch
HookRegistryonLevel(Level, callable): intRegister a callback for all events at/above Level (dispatched by PsrBridge or explicit fire())
HookRegistryfire(Level, psrLevel, msg, ctx)Dispatch to all matching handlers
HookonLevel(Level, string, string, array)Interface for structured hook implementations
PartsOrdernew(?list)Config DTO for log-part ordering
PartsOrderdefault(): selfPreset: timestamp, level, prefix, caller, message, fields
PartsOrdersyslog(): selfPreset: timestamp, level, message, fields (no prefix/caller)
PartsOrdermessageFirst(): selfPreset: message, level, timestamp, fields
PartsOrderhas(PART_*): boolCheck whether a part is included in the order
PartsOrderPART_TIMESTAMP, PART_LEVEL, PART_PREFIX, PART_CALLER, PART_MESSAGE, PART_FIELDSPart name constants
CallerFormatterfind(): ?stringWalk the call stack (bounded at 20 frames), return "basename:line" of the first frame outside the package, or null when none is found
LevelDebug, Info, Warn, Error, FatalEnum: charmbracelet/log-aligned int deltas (-4, 0, 4, 8, 12) — deliberately NOT RFC 5424/syslog severities
TextFormatternew(bool, ?string, bool, ?bool, ?Styles, ?PartsOrder)Human-readable formatter with ANSI color; useColors is tri-state (null consults the terminal probe), null styles/partsOrder fall back to defaults
JsonFormatternew(bool, ?string)JSON object per log line; optional timeFormat (default DateTimeInterface::ATOM)
LogfmtFormatternew(bool, ?string)Logfmt key=value format; optional timeFormat (default DateTimeInterface::ATOM)
LoginstallPanicHandler()Install global panic handler (catches fatal errors + uncaught exceptions)
LogrestoreTerminal()Restore terminal from altscreen mode
LogsetLogger(Logger)Set the global logger instance
Loginfo(msg, ctx)Static shorthand — delegates to global logger
Logdebug/warn/error/fatal(msg, ctx)Static shorthands for each level

Demos.

The flagship demo, recorded as a GIF with VHS. Regenerated automatically on every push that touches the source.

All log levels + formats

All log levels + formats

Debug / Info / Warn / Error / Fatal across Text / JSON / Logfmt formatters.