Logging and audit trails
Diagnostic logs help you explain why an operation behaved as it did. An audit trail records selected activity against a session: a start, a transition, a restored session or a blocked choice. Keeping both channels makes it possible to connect the reason for an incident with the action your application accepted or rejected.
ExecKernel provides separate interfaces for those purposes. Your application chooses the destinations and retention policy. The engine supplies operational fields such as graph, session, operation, node and edge identifiers; your logger or audit implementation decides how those records are stored and searched.
Connect the two channels
Section titled “Connect the two channels”A diagnostic logger implements LoggerAdapterInterface. Psr3LoggerAdapter connects that interface to a PSR-3 logger already used by your application. It forwards the level, message and context to that logger; it does not choose a file, rotate logs or apply a second privacy policy to arbitrary application messages.
An audit sink implements AuditLoggerInterface::log(AuditEvent $event). Each AuditEvent carries an event name, an audit ekCode, a sessionId, selected data and a timestamp. This structured shape lets your application store activity separately from free-form diagnostic messages.
The complete example provides two small application classes: ProductionJsonLogger, a PSR-3 logger that writes JSON lines, and ProductionAuditLogger, which serializes those AuditEvent fields. With writable streams prepared for them, composition is:
$logger = new Psr3LoggerAdapter(new ProductionJsonLogger($diagnosticStream)); $audit = new ProductionAuditLogger($auditStream); $engine = (new ExecKernelFactory())->build(logger: $logger, auditLogger: $audit);The factory passes the same collaborators to the relevant runtime components. Supplying only the diagnostic logger does not also install an audit sink. Without a configured collaborator, the corresponding null implementation produces no output.
For the example, both streams use php://temp so the final report can show their records. In your application, pass your existing PSR-3 logger and an audit implementation connected to your chosen storage. ArrayAuditLogger is another useful in-memory sink for inspecting records, but its contents last only as long as that object.
Align successful activity with a confirmed save
Section titled “Align successful activity with a confirmed save”A result record means the engine completed the operation that produced it. Your application may still need to save the returned state. If an audit entry must describe a saved transition, delay successful runtime observations until the save is confirmed.
This is the deferred-delivery mechanism introduced in Events and listeners: calling the engine with deferEvents: true returns an EngineResult whose eventBatch can be published or discarded. The batch also holds the operation’s log, trace and audit observations for delivery. It is an in-process handle; publishing it does not make storage and external delivery one transaction.
The example’s application helper checks both the store’s persisted flag and the returned state before publishing:
function loggingConfirmResult(SessionStoreInterface $sessions, string $sessionId, EngineResult $result): void{ try { $saved = $sessions->save($sessionId, $result->state); if (!$saved->persisted || $saved->state->toArray() !== $result->state->toArray()) { throw new RuntimeException('The store did not confirm the requested state.'); } } catch (Throwable $failure) { $result->eventBatch?->discard(); throw $failure; } $result->eventBatch?->publish();}If saving fails, the helper discards the batch and propagates the failure. If saving succeeds, it publishes the observations. The same ordering applies to starting a session and choosing an edge. A rejected operation throws before returning a successful result; its diagnostic observations remain useful and are delivered without publishing successful transition records.
This example assumes sequential requests for one session. Coordinate competing requests using the approach in Concurrency and session revisions. Deferring records does not itself protect a later application save from another request.
Follow one rejected and one accepted choice
Section titled “Follow one rejected and one accepted choice”We will reuse the learning-choice graph from Anatomy of a graph. At node 10, edge 101 opens a reading guide at terminal 20; edge 102 opens practice at terminal 30, provided practiceEnabled is true. That small decision makes the difference between an attempted choice and a completed transition visible.
The complete example starts the session with practiceEnabled: false. Submitting practice therefore throws ForbiddenEdgeException, whose code is EK-SEC-NAV-002. The application keeps the saved state at node 10 and can offer the guide instead. The accepted guide choice uses the deferred save-and-publish helper:
$guide = $engine->choose( $graph, $start->state, 101, 'en', sessionId: $sessionId, timestamp: 1700000010, deferEvents: true, operationId: 'guide-confirmed', ); loggingConfirmResult($sessions, $sessionId, $guide);sessionId associates the observation with the application’s session. operationId distinguishes this choice from the rejected one. The example uses readable, fixed operation IDs to make the records easy to compare; a real request needs its own operation identity, or can use the engine’s generated default.
These are selected fields from the two diagnostic records produced by that sequence:
[ { "level": "warning", "message": "Condition blocked edge", "context": { "graph_code": "learning-path", "session_id": "learning-log-session", "operation_id": "practice-rejected", "event_phase": "diagnostic", "ek_code": "EK-RULE-003", "edge_id": 102 } }, { "level": "info", "message": "Navigation step", "context": { "graph_code": "learning-path", "session_id": "learning-log-session", "operation_id": "guide-confirmed", "event_phase": "result", "ek_code": "EK-ENGINE-NAVIGATION-STEP", "edge_id": 101 } }]The warning explains the blocked condition. The result log describes the accepted transition. EK-RULE-003 identifies the rule observation; the thrown navigation exception uses EK-SEC-NAV-002. Their relationship comes from the same session and operation, so do not require all layers to report an identical code.
The audit channel describes the same sequence in its own vocabulary:
| Operation | Audit record | Audit code | Meaning |
|---|---|---|---|
learning-start |
SESSION_STARTED, NODE_VISITED |
EK-AUD-100, EK-AUD-200 |
The initial state was saved and its batch published. |
practice-rejected |
RULE_BLOCKED_EDGE |
EK-AUD-300 |
A diagnostic record of the blocked choice; no EDGE_TAKEN is published for it. |
guide-confirmed |
EDGE_TAKEN, NODE_VISITED |
EK-AUD-201, EK-AUD-200 |
Edge 101 moved the session from 10 to 20. |
guide-confirmed |
TERMINAL_REACHED, SESSION_TERMINATED |
EK-AUD-202, EK-AUD-103 |
The confirmed result reached the terminal node. |
AuditEvent::ekCode classifies the audit record. Its data can also contain a runtime ek_code, such as EK-RULE-003 inside RULE_BLOCKED_EDGE; retain the distinction when indexing them. Runtime audit calls require a nonempty session ID, so provide sessionId explicitly when you need this trail from direct engine calls.
Keep enough context to investigate
Section titled “Keep enough context to investigate”The built-in runtime observation path selects operational metadata before sending records to sinks. It does not forward arbitrary session context, history, credentials or entire payloads. Treat this as the engine’s export policy; an application message sent straight to Psr3LoggerAdapter is still whatever your application supplied.
| Information | Investigation use | Handling in your application |
|---|---|---|
graph_code, graph_version |
Identify the definition and revision involved. | Keep these alongside the incident; the numeric flow_id may be absent. |
session_id |
Find activity for one session. | Restrict access and retention; a session ID can still identify activity even without a person’s name. |
operation_id |
Join observations from one start, choice or resume. | Keep it separate from a distributed trace ID and from a storage revision. |
observation_id, observation_sequence, event_phase |
Distinguish records and their order within an operation; separate diagnostic and result observations. | Preserve them when reshaping records for your log service. |
ek_code, node and edge identifiers |
Locate the failed check or completed step. | Prefer these structured fields over copying exception text or business data. |
| Application-specific context | Add a fact needed by your own investigation. | Select explicit fields and decide their privacy treatment before they reach a sink. |
Observation delivery is best effort. A logger failure must not overturn the runtime outcome. If an audit sink throws, the engine attempts an AUDIT_LOG_FAILURE record through that same sink and suppresses a further failure. That fallback cannot prove the original record was stored. Monitor the destination independently when missing audit records require operational attention; the interface does not provide an immutable ledger or a compliance guarantee.
Relate HTTP logs to runtime records
Section titled “Relate HTTP logs to runtime records”The API’s ExecKernelLoggingMiddleware writes a compact response record with trace_id, normalized endpoint, method, HTTP status and an ek_code extracted from an error response when available. Its default destination is PHP’s error_log; an application embedding the middleware can provide a callable destination.
That HTTP record answers which request returned which result. It does not contain the full runtime audit trail or request body. Use the response’s X-Trace-Id to find the HTTP entry, then the application’s correlation data to connect it to runtime observations. Tracing and error telemetry explains the distinction between that request identifier and an OpenTelemetry parent.
Complete example
Section titled “Complete example”logging-audit.php contains the two sink implementations, engine composition, confirmed saving and both choices. It uses the unchanged learning-path definition. With your application’s autoloader available, an optional run is:
php logging-audit.php learning-path.json ./var/observability-sessionsThe report includes the rejection code, saved node 20, diagnostic records and audit records. The observation timestamps are fixed for the example. The state directory persists the session; the demonstration’s log streams remain in memory. Replace those streams with the destinations your application operates when adapting the integration.