juksgraphic / flightphp-debug
Alpine debug bar, redacted Tracy panels, exception pages and log reader for FlightPHP and Eloquent.
Requires
- php: ^8.4
- flightphp/core: ^3.18.1
- illuminate/database: ^12.0
- tracy/tracy: ^2.12
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.75
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^13.1
Suggests
- flightphp/tracy-extensions: Flight panels; its Database, Request, Flight and Response tabs are replaced by this package
Provides
None
Conflicts
None
Replaces
None
README
Development-only debug tools for FlightPHP + Eloquent + htmx + Alpine.js:
- the JG debug bar: Next.js-style dev tools built with Alpine.js. It replaces Tracy's visible bar;
- redacted Tracy panels, used when Tracy's own bar is switched back on.
Tracy stays underneath for exceptions (BlueScreen) and logs.
JG debug bar
A black JG monogram button sits in a corner. A red pill appears next to it when the request has issues.
| Element | Content |
|---|---|
| Menu (click the button) | Issues, route, status · time · memory, queries, htmx requests, request, app, preferences |
| Issues | PHP warnings/notices (file:line, editor link), repeated queries (possible N+1), slow queries, bdump() count |
| Queries | Highlighted SQL with redacted values, repeated/slow badges, "only issues" filter, copy button |
| htmx | Partial htmx requests (hx-get…): method, path, status, time, queries, issues |
| Request | Summary, headers, GET/POST, files, cookie names, whitelisted server keys (environment hidden) |
| App | $app->get() redacted, as collapsible trees |
| Preferences | Corner, theme (site/light/dark), Tracy bar on/off, hide for the session, reset |
Shortcuts: Alt+Shift+D opens the menu (and brings back a hidden bar), Esc closes, ← → switch tabs.
Hidden for the session: a small semi-transparent JG dot stays in the corner. Click it to bring the bar back.
How it works
Response::send()
└─ body callback (before APM flushes the query log)
├─ QueryLogReader::capture()
└─ DebugBar::handle()
├─ Eligibility::refusal() 9 rules, see below
├─ eligible → SnapshotBuilder → bar.phtml → BarInjector (before last </body>)
└─ htmx fragment → "X-JG-Debug" summary header (JSON, redacted)
- One snapshot per request. It is built from existing sources only (query log, Flight request/response, Tracy
warnings). It is redacted once, then embedded as JSON escaped so it cannot close its
<script>tag. - Alpine.js: the page's own Alpine instance is used, with no second copy. The component registers on
alpine:init, or immediately if Alpine is already there. Preferences use@alpinejs/persistwhen present. Without Alpine, the button stays visible but inert. - Assets inline, with the CSP nonce from
$app->get('csp_nonce'). There is no browser-cache issue. - htmx:
hx-boostnavigations are full pages, so the bar is injected again with the new page's data.HX-Locationnavigations are not "boosted", but they replace<body>with a full document. An htmx request with noHX-Targetheader whose response contains<html>is treated as a page navigation and gets the bar. Server redirects (302/303) on boosted requests are followed by the browser and also get the bar.- Safety net: when a bar initializes, it removes any older bar left on the page.
The open panel survives through
sessionStorage. - Partial requests never receive the bar. Their summary header feeds the htmx tab through an Alpine store that survives body swaps.
#jg-debugcarries no Alpine binding. The component lives on.jg-root, which has no id. After a swap, htmx "settles" elements that keep the same id and resets theirclassandstyle. That used to wipe the theme class (the bar fell back to light) andx-showstyles. Keep state classes off#jg-debug.
- Never breaks a page: any failure leaves the body untouched. A failing source is listed as "Unavailable" in the panel footer.
Injection rules
The bar is only added to responses that are:
- not
HEAD; - not a partial htmx request (
HX-RequestwithoutHX-Boosted); - not
X-Requested-With: XMLHttpRequest; - not
204or3xx; text/html, or without aContent-Typeheader;- not an attachment;
- not compressed;
- not already injected;
- containing a
</body>tag.
JSON, downloads and fragments are returned byte for byte.
Tracy's own bar
Hidden by default. The Tracy bar preference sets a jg_debug_tracy cookie and reloads the page.
DebugServiceProvider::beforeEnable() reads it before Debugger::enable().
Use it for Tracy-only features such as inspecting bdump() output.
Exception page
Uncaught exceptions get a kit-styled page (Next.js error-overlay style), on screen in development and in the log files. Tracy still captures and logs everything.
| Where | What you get |
|---|---|
app/log/exception--…--{hash}.html |
Kit page. Same name as before, so the exception.log line still links to it |
app/log/exception--…--{hash}--tracy.html (+ .md) |
Tracy's full BlueScreen, linked from the kit page |
| Browser (dev, HTML request) | Kit page, HTTP 500, with Tracy's BlueScreen in a collapsible sandboxed iframe |
| htmx request (boosted or fragment) | Kit page with an X-JG-Exception header, shown by the bar in a full-screen overlay (Esc closes it) |
| Fatal error (out of memory, parse error) | Kit page too, when beforeEnable() ran before Debugger::enable() |
| Plain AJAX, CLI | Tracy's default behavior (CLI still writes the kit file) |
What the page shows:
- class, message and code;
file:linewith an editor link, and the highlighted source excerpt;- the call stack, with
vendor/frames grouped and collapsed, and source for app frames; - the previous exceptions ("Caused by");
- request context (method, URL, route) or the CLI command.
Values are redacted, and environment variables are never shown. It works in light and dark, with Copy and theme buttons. It is self-contained (inline CSS/JS, no Alpine, no CDN), because log files are opened straight from disk.
How it works:
ExceptionLoggerextendsTracy\Logger(officialDebugger::setLogger()) and overrideslogException(). It writes Tracy's file first, then the kit page. If the kit page fails, it copies Tracy's file: an exception is never left unlogged.ExceptionScreenis the uncaught exception handler (installed after Tracy;flight.handle_errorsis set tofalse). Any failure falls back toDebugger::exceptionHandler(). htmx requests are rendered too, even when Tracy's bar addsX-Tracy-Ajaxto them: otherwise Tracy would show its BlueScreen instead of the kit page.FatalErrorCatcher: fatal errors never reach exception handlers, Tracy renders them from its shutdown function.beforeEnable()registers a shutdown function before Tracy's, which renders the kit page and clears the error so Tracy does not render it again. WithoutbeforeEnable(), fatal errors keep Tracy's BlueScreen.bar.jswatcheshtmx:beforeSwap: a response flaggedX-JG-Exceptionis not swapped, it opens in a sandboxed overlay mounted under<html>(it survives hx-boost swaps).RequestScrubber: Tracy masks sensitive keys, not URLs. While Tracy writes or renders,REQUEST_URI,QUERY_STRINGandHTTP_REFERERare swapped with their redacted version, then restored.?token=…no longer appears in Tracy's BlueScreen, its file or theexception.logline.- In development, Tracy alone only displays browser exceptions. With the package they are also logged, so each
error seen in the browser has its file in
app/log/.
Disable with new DebugConfig(exceptionPage: false).
Limits:
- Plain AJAX requests (
X-Requested-With, noHX-Request) keep Tracy's behavior: they may expect JSON. - Exception messages are shown as is: a message built with a secret (for example a SQL error with values) is not redacted, in this page or in Tracy.
- In production (
protectLogs()), only the log file uses the kit page. Visitors get Flight's generic 500 page, or your own page witherrorPage(see below).
Redacted Tracy panels
They replace four flightphp/tracy-extensions panels and harden Tracy itself.
| Panel | Replaces | Why |
|---|---|---|
| Eloquent queries | Database | The original only sees PdoQueryCapture, so it is always empty with Eloquent |
| Request | Request | The original prints $_SERVER (which holds every .env secret), $_POST and cookies in clear |
| Flight | Flight Vars | The original prints $app->get('config') with passwords in clear |
| Response | Response | The original prints Set-Cookie in clear, has no status colors, and its light-grey body box is unreadable in dark mode |
The package also gives Tracy's BlueScreen a scrubber. JWT_SECRET, DB_PASSWORD and the like are masked on screen
and in the exception--*.html files written to the log directory.
Request panel
Sections: Summary (method, URL, IP, route, HTMX mode), Headers, Query, Body, Files, Cookies, Server.
- Sensitive keys are masked everywhere, including nested arrays, headers and query strings in URLs.
- Cookies: names only, values always masked.
- Files: name, type, size and error only. The temporary path is never shown.
- Server: whitelisted request keys only (
REQUEST_*,SERVER_*,REMOTE_*…). Any key coming from the environment ($_ENV,getenv()) is dropped.
Response panel
- Tab: the status code, colored by group: 2xx primary, 3xx info, 4xx warning, 5xx danger. The JG bar uses the same colors.
- Panel: status with reason phrase, content type, size, redacted headers (
Set-Cookie,Authorization…), and a body preview. JSON is pretty-printed and redacted; text bodies go throughredactText(); HTML is shown as source. Previews stop at 20 KB. - Output echoed after headers were sent (for example a
notFoundview) is not in Flight's response, so it shows as empty. - The Tracy theme also fixes the hard-coded light-grey
<pre>of the remaining tracy-extensions panels (Session) in dark mode.
Flight panel
Shows $app->get(), redacted recursively. For example, config.database.password appears as ••••••.
Eloquent queries panel
- Tab: number of queries and total time. The tab turns red when a query is slow or repeated.
- Panel: every query with its bound values inlined and its time.
- Repeated (yellow): the same SQL ran several times. This often means N+1.
- Slow (red): the query took at least
slowQueryMs(100 ms by default).
- Sensitive values are masked as
••••••.- Masked:
password = ?,SET token = ?,INSERT (…, remember_token). - Values longer than
maxValueLengthare truncated.
- Masked:
Requirements
PHP 8.4+, flightphp/core ^3.18.1, illuminate/database ^12 and tracy/tracy ^2.12.
Installation
composer require juksgraphic/flightphp-debug
The package is required in every environment. What it activates depends on Tracy's mode.
app/config/services/debugger.php, in two places:
// 1. BEFORE Debugger::enable(): Tracy serves its assets inside enable() if (ENVIRONMENT === 'development' && class_exists(DebugServiceProvider::class)) { DebugServiceProvider::beforeEnable(); // Tracy theme + htmx fix, fatal errors, Tracy bar hidden unless cookie } Debugger::enable(/* ... */); // 2. AFTER Debugger::enable() if (class_exists(DebugServiceProvider::class)) { $debug = new DebugServiceProvider(new DebugConfig(slowQueryMs: 100.0, basePath: PROJECT_ROOT)); Debugger::$productionMode === false ? $debug->register($app, $app->capsule()->getConnection()) // development: everything : $debug->protectLogs($app); // production: log protection only }
Development (register()) |
Production (protectLogs()) |
|
|---|---|---|
| JG debug bar, redacted Tracy panels, Tracy theme | ✅ | — |
| Kit exception page on screen | ✅ | — (Flight's generic 500 page, or errorPage) |
Kit exception page in app/log + Tracy's file |
✅ | ✅ |
URL secrets masked in Tracy files and exception.log |
✅ | ✅ |
| BlueScreen scrubber | ✅ | ✅ |
| Flight-handled exceptions logged through Tracy | (Tracy handles them) | ✅ (Flight::map('error'), default 500 response and flight.error event kept) |
Custom 500 page (production)
new DebugConfig(errorPage: static fn (Throwable $e): string => (string) file_get_contents(__DIR__ . '/500.html'));
After logging, the package sends that HTML with a 500 status (no cache) and still triggers flight.error. Echoed
output is dropped. If the closure throws, the failure is logged and Flight's generic page is sent instead. Do not
show $e to visitors. For fatal errors, also point Tracy's own setting Debugger::$errorTemplate to a PHP file.
Before protectLogs(), exceptions caught by Flight in production (flight.handle_errors = true) only went to
error_log(). They never reached app/log.
Log explorer (read-only)
Logs\LogReader reads Tracy's log directory for an admin page. The starter kit uses it at
/admin/monitoring/logs (super-admin).
$reader = LogReader::forDirectory(Debugger::$logDirectory, new DebugConfig(basePath: PROJECT_ROOT)); $result = $reader->read(LogQuery::fromArray($_GET)); // entries, total, levelCounts, page, truncated $reader->exceptions(); // logged exceptions with titles, newest first $reader->exceptionFile($name); // whitelisted path or null
- Whitelist only: level files (
critical/exception/error/warning/info/debug.log) and{level}--{date}--{time}--{hash}[--tracy].html. A requested name is never concatenated to a path: it must match the pattern and exist (../,exception.logand other names givenull). - Bounded memory: files are read backwards in 64 KB chunks. Only the last 5,000 lines per file are scanned, and the
result says so (
truncated). - Redacted:
key=valuesecrets in messages and URLs (password=,?token=…) are masked, and the project root is stripped from paths. - Tolerant: malformed lines are kept and shown as is.
- Read-only: nothing is ever written, moved or deleted.
LogQuery::fromArray()validates raw input: unknown level or source, odd page sizes and invalid dates fall back to safe defaults.- Serving an exception page: send it with
Content-Security-Policy: sandbox allow-scriptsand theX-JG-Debug-Skipheader (the JG bar is never injected into it). Show it in an<iframe sandbox="allow-scripts">. The page accepts#theme=dark|light, because a sandboxed frame cannot read the parent's storage.
Theme
assets/tracy-theme.css restyles Tracy with the starter kit look. It is appended to Tracy's assets through
Debugger::$customCssFiles.
- Colors come from the kit tokens, with fallbacks:
var(--color-primary, #63921e),--color-surface,--color-outline… On a page without the kit CSS, the bar keeps readable default colors. - Dark mode follows the kit toggle (the
darkclass on<html>), not the OS preference. - Package panels use
jg-*classes only. Templates contain no inlinestyle. - Tracy's native panels (timing, Response, dumps) inherit fonts and colors only. Their internal structure is untouched.
htmx compatibility
Tracy mounts its bar inside <body>, and hx-boost replaces the content of <body>.
Without a fix, the bar disappears after a boosted navigation, and the next AJAX bar crashes with
Cannot read properties of null (reading 'Tracy').
assets/tracy-htmx.js (registered through Debugger::$customJsFiles) mounts Tracy's layer and its AJAX
script loader under <html>, outside any swap target. The bar stays in place, and each boosted page
appears as an AJAX row with its own panels.
Cache: Tracy bundles this CSS and JS into its JS asset, which browsers cache for 10 days. Tracy keys that URL on
its own version and the page URL only, so an edited theme or htmx fix used to stay stale (old styles, and the bar
vanished on hx-boost until a hard refresh). AssetCacheBuster, registered by beforeEnable(), adds
_jg_assets={hash of the custom files} to the URL: any edit gives a new URL. It appends the parameter to
REQUEST_URI at shutdown, just before Tracy renders its bar, because Tracy builds the URL from it.
Configuration
| Option | Default | Purpose |
|---|---|---|
slowQueryMs |
100.0 |
Slow query threshold (ms) |
maxValueLength |
100 |
Truncate longer bound values |
extraSensitiveKeys |
[] |
Extra column names to mask, e.g. ['siret'] |
databasePanelId |
tracy-extensions id | Tracy slot for the SQL panel |
requestPanelId |
tracy-extensions id | Tracy slot for the Request panel |
flightPanelId |
tracy-extensions id | Tracy slot for the Flight panel |
responsePanelId |
tracy-extensions id | Tracy slot for the Response panel |
injectBar |
true |
Inject the JG debug bar |
basePath |
null |
Prefix stripped from file paths in Issues (PROJECT_ROOT in the kit) |
cspNonceKey |
csp_nonce |
Flight variable holding the CSP nonce for inline assets |
exceptionPage |
true |
Kit exception page on screen and in log files |
errorPage |
null |
Production only: Closure(Throwable): string returning your 500 page HTML. Never shown in development |
A key is masked when its whole name, or one of its _ / - segments, matches a sensitive key.
For example, password_hash, remember_token, JWT_SECRET and X-Api-Key are masked.
The same rules feed Tracy's keysToHide and BlueScreen scrubber.
How it works
SQL ─▶ Eloquent query log (enabled if needed)
Response::send() ─▶ body callback: QueryLogReader snapshots the log
flight.response.sent ─▶ APM may flush the log (sampled requests)
shutdown ─▶ Tracy renders the bar ─▶ DatabasePanel = snapshot + later queries
| Class | Responsibility |
|---|---|
DebugServiceProvider |
Wires panels, hooks and Tracy protection |
DebugConfig |
Options and default sensitive keys |
Redactor |
Masks and truncates values (single place), Tracy scrubber |
Http\RequestReader |
Builds redacted request sections |
Http\ServerFilter |
$_SERVER whitelist, environment keys dropped |
Tracy\TemplateRenderer |
Renders templates/*.phtml (escaper + Tracy dumper) |
Tracy\RequestPanel / Tracy\FlightVarsPanel / Tracy\ResponsePanel |
IBarPanel, no logic |
Database\SqlHighlighter |
Escaped SQL with keywords, strings, numbers and masked values highlighted |
Database\QueryLogReader |
Reads and snapshots Eloquent's log |
Database\PlaceholderMapper |
Finds the column behind each ? |
Database\QueryFormatter |
Inlines redacted values into SQL |
Database\QueryAnalyzer / QueryReport |
Totals, repeated and slow queries |
Tracy\DatabasePanel |
IBarPanel, renders templates/*.phtml |
Known limits
- No source location (file and line) per query. Eloquent's log does not record it.
It would require
illuminate/eventsplus a dispatcher on the connection. - Streamed routes skip the body callback. Only the live log is shown for them.
- The column guess covers common SQL shapes. Unknown placeholders are shown unmasked.
- Read/write type is not shown. Without a read/write split, Eloquent always reports
write. tracy-extensionsalso adds a "Flight Variables" panel to the BlueScreen. It usesprint_r, so the scrubber cannot reach it, and there is no API to remove it. It only appears for exceptions without a message.- Tracy's bar loader script reuses the current page URL, query string included. This is the URL already in the address bar.
- BlueScreen files written before installing the package may still contain secrets. Check
app/log/exception--*.
Testing
composer test # PHPUnit composer analyse # PHPStan composer format # PHP CS Fixer
Working on the package from an app
Point the app at a local clone with a temporary path repository. Do not commit it:
composer config repositories.flightphp-debug path ../flightphp-debug composer require juksgraphic/flightphp-debug:@dev
Revert with composer config --unset repositories.flightphp-debug and composer require juksgraphic/flightphp-debug:^0.1.
Architecture
Modules, class dependencies and runtime flows are documented in ARCHITECTURE.docx.
It is generated from the code: run composer docs (needs Python 3, Graphviz and Node.js). See
docs/architecture.
Changelog
See CHANGELOG.
License
The MIT License (MIT). See License File.