Skip to content
Belikhun edited this page Sep 15, 2026 · 1 revision

📜 Trace

Trace is blink's audit log: who did what to which record, kept in the traces table. It answers "what happened to this order last Tuesday", which is a different question from the one the dispatch trail (Lightrail) or the error reports answer.

Everything model-shaped is recorded for you. Anything else, you record with one fluent call.

Recording an entry

use Blink\Trace;

Trace::info(Trace::APP, "order.shipped")
	-> mode("update")
	-> target($order)
	-> field("carrier")
	-> payload(array( "carrier" => "DHL", "tracking" => "JD0123" ))
	-> record();

Trace::info() and its siblings (debug, notice, warning, error, critical, alert, emergency) start a builder at that level. Trace::entry() starts one at the default level, info.

The two arguments every entry needs:

Argument Meaning
component Who is speaking. Trace::CORE ("blink") for the framework, Trace::APP ("app") for the application, or any short name of your own.
message What happened. Either a lang key, resolved through __() when the entry is shown, or a literal sentence. Both may carry {name} placeholders.

The builder methods, all optional:

Method Records
level(string|int) Severity. A name such as "warning" or its code.
mode(string|int) The kind of action: view, create, update, delete, report, or one a module registered. Defaults to report.
scope(?string) A free grouping, such as "model" or "billing".
field(?string) A short indexed key, up to 32 characters, for the subject of the entry. Filter on this rather than searching payloads.
actor(int|UserBase|null) Who did it. Left unset, the signed-in user is recorded.
source(?Model) The record the action came from.
target(?Model) The record the action was done to.
payload(array|object|string|null) Anything else worth keeping, stored as JSON. Its keys double as message placeholders.
at(int) When it happened, for an entry recorded after the fact.

record() hands the entry to the writer and returns the in-memory Trace\Entry. Calling it twice returns the same entry.

When entries are written

Recording an entry costs the request nothing. The writer resolves what depends on the request right away (the actor, the client address, the time) and queues the row. The queue is written in one insert when the request ends, from the shutdown handler, after the response has gone out.

Two things force an earlier write:

  • the queue reaching 200 entries, so a command that records thousands does not hold them all until it exits;
  • Trace::flush(), when you need the rows in the table now.

A Ticker runner flushes after every task, so a task's entries land when the task finishes rather than when the runner eventually exits.

If the batched insert fails, the writer falls back to one insert per row, so a single bad row loses only itself. Those failures go to the server log; recording them in the audit log would only queue them again during shutdown.

Displaying an entry

An entry stores its message as written. getDisplayMessage() turns it into a sentence:

  1. If a lang string exists for the message, that string is used.
  2. Otherwise the message itself is used.
  3. Either way, {name} placeholders are filled from the entry and its payload.

Placeholders every entry offers:

Placeholder Value
{actor} The actor's display name, or "the system" when there is none
{actorIP} The client address
{model} The target's class name made readable: App\Model\PurchaseOrder reads as Purchase Order. Falls back to the source.
{target}, {source} The same, for one side only
{id} The target id, or the source id, or the entry id
{targetClass}, {targetID}, {sourceClass}, {sourceID} The raw references
{component}, {scope}, {field} As recorded
{level}, {levelLabel}, {mode}, {modeLabel} The level and mode by name and by translated label
{created} The timestamp

Payload keys override these, so payload(array( "id" => "ORD-42" )) changes what {id} shows.

jsonSerialize() returns the entry with levelMeta, modeMeta and displayMessage filled in, ready for an API response.

Levels and modes

Levels and modes are stored as codes, so the table stays narrow and levels sort by weight. The names, labels and colors live in two registries.

Level Code Mode Code
debug 10 view 1
info 20 create 2
notice 30 update 3
warning 40 delete 4
error 50 report 5
critical 60
alert 70
emergency 80

A module adds its own from attach() by type-hinting the registry it wants:

use Blink\Module;
use Blink\Trace\LevelRegistry;
use Blink\Trace\ModeRegistry;

class AppModule extends Module {
	public function attach(LevelRegistry $levels, ModeRegistry $modes): void {
		$levels -> register(45, "security", "app.trace.level.security", "red");
		$modes -> register(10, "export", "app.trace.mode.export", "purple");
	}
}

The third argument is a lang key for the label. Codes and names must be unique; registering one twice throws a CodingError, and so does recording an entry with a level or mode nobody registered.

Model auditing

Blink\Observer\ModelAuditObserver listens to ModelCreated, ModelUpdated and ModelDeleted and records one entry per change:

Event Mode Message
created create {model} #{id} was created by {actor}.
updated update {model} #{id} was updated by {actor}, {changeCount} field(s) changed.
deleted delete {model} #{id} was deleted by {actor}.

An update carries the delta in its payload: changeCount, and changes as field => [old, new] with each value cut at 255 characters. The updated stamp is left out, since it moves on every save. A save that changed nothing is not recorded.

The component is blink for models under Blink\ and app for everything else. Lightrail's trail models and Trace's own entries are never audited; their rows are bookkeeping, not something anyone did.

To keep a model of your own out of the log, wrap the observer with an Ether handler middleware that returns without calling $next when the event is about that class. Lightrail records the handler as skipped and nothing is written. Most applications want the default.

Reading the log

php core/blink trace:list
php core/blink trace:list --level=warning --component=app
php core/blink trace:list --mode=update --target="App\Model\Order"

trace:list shows the newest entries with their display message. From code, Trace\Entry is an ordinary model:

use Blink\Trace\Entry;

$history = Entry::query()
	-> where(Entry::col("targetClass"), Order::class)
	-> where(Entry::col("targetID"), $order -> id)
	-> sort(Entry::col("created"), "DESC")
	-> all(0, 50);

Every listing is newest first within some filter, so each of component, scope, field, mode, level, actor_id, the target pair and the source pair is indexed together with created.

Retention

php core/blink trace:purge
php core/blink trace:purge --days=90 --force

trace:purge deletes entries older than CONFIG::$TRACE_RETENTION_DAYS (365 by default) in passes of CONFIG::$TRACE_PURGE_BATCH rows, so a table holding a year of entries never becomes one statement holding locks for the duration. The core module runs it every night at 03:30 through Ticker. A retention of 0 keeps everything, and the nightly run respects that.

Configuration

Setting Default Meaning
CONFIG::$TRACE_RETENTION_DAYS 365 Days an entry is kept. 0 keeps every entry.
CONFIG::$TRACE_PURGE_BATCH 5000 Rows deleted per statement by trace:purge.

Building blocks

Class Purpose
Blink\Trace The facade: level starters, flush(), the registries
Blink\Trace\Builder Assembles one entry and hands it to the writer
Blink\Trace\Writer Resolves request context, queues rows, writes them in one insert
Blink\Trace\Entry The model behind the traces table, with getDisplayMessage()
Blink\Trace\LevelRegistry, Blink\Trace\ModeRegistry Names, labels and colors for the stored codes
Blink\Trace\Mode The stored codes of the built-in modes
Blink\Observer\ModelAuditObserver Records every model change

Clone this wiki locally