Documentation menu

Architecture

Logging and debugging

This page covers where Taphra writes its logs, how to write your own lines, the request ID that ties the lines of one request together, the request log behind php taphra debug:request, and the debugging helpers.

Contents

#

Where log lines go

#

With the default file driver, each line is one JSON object appended to app/tmp/Log/app.log:

JSON
{"ts":"2026-11-30 09:14:02","rid":"84e14fda2892e206","msg":"Low stock","type":"WARNING","uri":"/orders","url":"https://example.com/orders","cat":"stock","pid":4120,"tid":"","ip":"203.0.113.7","os":false}
Field Content
ts local time of the write
rid the request ID, the same on every line of one request
msg the message: a string, or an array or object as JSON
type the level (DEBUG, MESSAGE, NOTICE, WARNING, ERROR)
uri, url the request path and URL (null and localhost on the command line)
cat the category you passed, empty by default
pid, tid process id, thread id where PHP has one
ip, os client address and a guess at the client's operating system

The settings live under logging in app/Config/app.yml:

YAML
all:
  logging:
    method: file        # file | syslog | null, or the name of your own driver
    # level: notice     # lowest level written (debug, message, notice, warning, error)
    # log_requests: true

Levels

#

The five levels, from lowest to highest, are debug, message, notice, warning and error (the Logger::TYPE_* constants). A line below app.logging.level is not written.

Without a level, development writes every level, and staging and production write notice and above. The framework's own "action ... start" and "action ... finish" lines are message lines, so they appear in development only. To change it per environment:

YAML
prod:
  logging:
    method: file
    level: warning

Writing log lines

#

Controllers, models and any class that extends Taphra\TaphraObject have log(), dbg(), notice() and warning():

PHP
namespace App\Lib;

use Taphra\Logger;
use Taphra\TaphraObject;

final class StockChecker extends TaphraObject
{
    public function check(string $sku, int $left): void
    {
        $this->dbg("checked $sku");                     // debug
        if ($left < 5) {
            // log(message, level = Logger::TYPE_MESSAGE, category = '')
            $this->log(['sku' => $sku, 'left' => $left], Logger::TYPE_WARNING, 'stock');
        }
    }
}

(new StockChecker())->check('A-100', 3);

$lines = file(APP_TMP_PATH . '/Log/app.log', FILE_IGNORE_NEW_LINES);
$last  = json_decode(end($lines), true);
echo $last['type'], ' ', $last['cat'], ' ', json_encode($last['msg']), "\n"; // WARNING stock {"sku":"A-100","left":3}

Outside those classes, use the global helpers. They write through the same logger, with the same level filter:

PHP
tphr_log('Import finished', \Taphra\Logger::TYPE_NOTICE, 'import'); // level defaults to notice
tphr_dbg('Cache miss for user 42');
tphr_notice('Payment provider slow');
tphr_warning('Disk 90% full');

err() and tphr_err() log at error level and then raise a PHP error with trigger_error(), E_USER_ERROR by default. PHP 8.4 deprecates that level in trigger_error(); throw an exception instead, which the error handler logs (see Errors and exceptions).

Named logs

#

Logger::entry() writes one line to a log of your choice. With the file driver the name is the file: app/tmp/Log/audit.log below. It writes the line whatever app.logging.level says, which suits an audit trail:

PHP
use Taphra\Logger;

// entry(message, level = Logger::TYPE_MESSAGE, category = '', log name = 'app')
Logger::entry('Refund approved by user 7', Logger::TYPE_NOTICE, 'billing', 'audit');

echo json_decode(file_get_contents(APP_TMP_PATH . '/Log/audit.log'), true)['msg'], "\n"; // Refund approved by user 7

PSR-3

#

Libraries that take a Psr\Log\LoggerInterface can have the container's logger, a Taphra\Logger\Psr3FileLogger that writes the same JSON lines to app/tmp/Log/app.log with the category psr3. Messages use PSR-3 {placeholder} interpolation:

PHP
use Psr\Log\LoggerInterface;

$logger = getContainer()->get(LoggerInterface::class);
$logger->warning('Webhook from {provider} retried', ['provider' => 'stripe']);

Psr3FileLogger writes to the file directly: in 1.0 it does not follow app.logging.method or app.logging.level. To hand a library a PSR-3 logger that uses the configured driver (syslog, null or your own), wrap that driver with Psr3LoggerBridge:

PHP
use Taphra\Logger;
use Taphra\Logger\Psr3LoggerBridge;

$psr = new Psr3LoggerBridge(Logger::getInstance());
$psr->error('Search index {index} unreachable', ['index' => 'products']);

The bridge follows the driver but, like Logger::entry(), not the level filter.

Drivers

#

app.logging.method picks the driver for every log name:

Method Writes to
file (default) app/tmp/Log/<name>.log, one JSON line per entry
syslog syslog(), with the level as the priority; journald, Docker and log shippers collect it
null (also none, off, false) nowhere: every line is discarded

The syslog driver reads two optional settings:

YAML
all:
  logging:
    method: syslog
    syslog:
      ident: myapp      # program name in syslog; default: the log name (app)
      facility: local0  # user (default), daemon, syslog, local0 to local7

method: null is handy in tests. Remember that a Psr3FileLogger keeps writing to its file even then (see PSR-3).

Your own driver

#

A driver is a class named <Method>Logger that extends Taphra\Logger\AbstractLogger and implements write(). The framework looks for Taphra\Logger\<Method>Logger, then App\Logger\<Method>Logger, then a global <Method>Logger, and falls back to the file driver. This one sends every line to standard error, which container platforms collect:

app/Logger/StderrLogger.php
<?php
// app/Logger/StderrLogger.php
namespace App\Logger;

use Taphra\Logger\AbstractLogger;

final class StderrLogger extends AbstractLogger
{
    /** Receives the JSON line built by prepare(). */
    public function write(string $message): bool
    {
        return file_put_contents('php://stderr', $message . "\n") !== false;
    }
}
YAML
prod:
  logging:
    method: stderr

AbstractLogger::getInstance() builds one instance per class and log name with a constructor that takes no arguments. A driver whose constructor needs arguments overrides getInstance().

Errors and exceptions

#

Outside development, the error handler logs every uncaught exception before it shows the error page: HTTP exceptions (a 404, a 403) at notice, other framework exceptions at warning, and anything else at error. With the default level, production therefore logs every 404. In development the debug page shows the exception instead.

Catching framework exceptions

#

Every exception class that Taphra and its packages define implements Taphra\TaphraExceptionInterface, whatever its base class: Taphra\Db\DbException, Taphra\Exceptions\HttpException and its 401, 403, 404 and 405 subclasses, Taphra\Ai\AiException, Taphra\Billing\BillingException, the container exceptions and the others. One catch handles any of them:

PHP
use Taphra\DatabaseConnection;
use Taphra\Exceptions\NotFoundException;
use Taphra\TaphraExceptionInterface;

$attempts = [
    fn() => getContainer()->get('search'),
    fn() => DatabaseConnection::load('app_master')->query('SELECT * FROM no_such_table'),
    fn() => throw new NotFoundException('No such order'),
];

foreach ($attempts as $attempt) {
    try {
        $attempt();
    } catch (TaphraExceptionInterface $e) {
        echo get_class($e), "\n";
    }
}
// Taphra\Container\NotFoundException
// Taphra\Db\DbException
// Taphra\Exceptions\NotFoundException

Argument mistakes caught by a package itself use PHP's own classes and are not covered: an unknown validation rule, a Crypt key shorter than 32 bytes or a malformed locale throws \InvalidArgumentException.

Request IDs

#

Every line carries rid, an ID that stays the same for the whole request: 16 hexadecimal characters, made on first use. Read it anywhere with Taphra\RequestId::get(), for example to show it on an error page or pass it to another service.

To carry an ID across services, put RequestIdMiddleware first in a PSR-15 entry (see Routing). It adopts the X-Request-ID header of the incoming request, or makes a new ID, and sends it back on the response. The header comes from the client unless a proxy in front of the app sets it.

PHP
use Nyholm\Psr7\ServerRequest;
use Taphra\Http\ActionDispatcherMiddleware;
use Taphra\Http\MiddlewarePipeline;
use Taphra\Http\RequestIdMiddleware;
use Taphra\RequestId;

$pipeline = (new MiddlewarePipeline())
    ->pipe(new RequestIdMiddleware())        // pass a name for another header: new RequestIdMiddleware('X-Correlation-ID')
    ->pipe(new ActionDispatcherMiddleware());

$response = $pipeline->handle(new ServerRequest('GET', '/health', ['X-Request-ID' => 'req-7f3a']));

echo $response->getHeaderLine('X-Request-ID'), ' ', RequestId::get(), "\n"; // req-7f3a req-7f3a

Behind the middleware, the ID is also the request attribute request_id and $_SERVER['HTTP_X_REQUEST_ID']. In FrankenPHP worker mode, RequestState::reset() clears it before each request, so no two requests share an ID.

The request log and debug:request

#

In development and staging you can record every request to app/tmp/Log/requests.log and read it back from the command line. Turn it on in app/Config/app.yml:

YAML
dev:
  logging:
    method: file
    log_requests: true

The setting is ignored in production. Then:

Shell
php taphra debug:request             # the last request
php taphra debug:request --tail=5    # the last five
php taphra debug:request --watch     # print new requests as they arrive (Ctrl+C to stop)
php taphra debug:request --log-file=/path/to/requests.log
Text
────────────────────────────────────────────────────────────
GET /health?x=1  2026-11-29 14:01:34

Headers:
  HTTP_HOST: 127.0.0.1:8000
  HTTP_USER_AGENT: curl/8.5.0
  HTTP_ACCEPT: */*

Each entry also lists the SQL statements the request ran, when there were any. In an app that runs a PSR-15 entry with RequestLogMiddleware (the API starter does), it also keeps up to 2 KB of each request body.

Credentials are not written: the values of Cookie, Set-Cookie and Authorization, of any header whose name contains token, secret, password, csrf, session or credential, or one of the words key, pass, pw, otp, code, jwt, pin, sid or auth (X-Api-Key, Mcp-Session-Id), and of query parameters and body fields (JSON at any depth, or form-encoded) with such names (password, _csrf_token, api_key, reset_code) are logged as [redacted]. A body that is neither JSON nor form data, or JSON that does not parse, is logged as [redacted] with its size, and a long token-like path segment (/reset/9f8e7d6c5b4a...) as [redacted]. Other values, user input included, are logged as sent, so keep the log to machines where that data may sit in a file.

Other log files

#

Two packages write files of their own next to app.log, whatever the logging method:

File Written by Content
app/tmp/Log/ai.log the AI providers, on every request provider, URL, model, and token usage or the error; the prompts and answers only with logging.payloads: true. Turn it off with logging.enabled: false in app/Config/ai.yml (see AI)
app/tmp/Log/billing.log the Stripe provider, on every call the action and the ids involved, such as create_subscription and the subscription id

app/tmp/ belongs outside version control and needs a rotation policy (logrotate or your platform's equivalent) in production.

Debugging helpers

#

dump($a, $b) prints each value in a styled <pre> block and carries on; dd($a, $b) does the same and stops the script. pr($value) prints print_r() output and vd($a, $b) var_dump() output, both in <pre>. All four print in every mode, so remove them before you deploy.

In development, the framework records every SQL statement of a request in Taphra\QueryLog. The debug error page shows them. You can turn the log on yourself, in a test or a script, and look for repeated queries:

PHP
use Taphra\DatabaseConnection;
use Taphra\QueryLog;
use Taphra\SchemaBuilder;

$db = DatabaseConnection::load('app_master');
(new SchemaBuilder($db))->create('skus', function ($t) {
    $t->id();
    $t->string('code', 20);
});

QueryLog::enable();
foreach ([1, 2, 3, 4] as $id) {
    $db->query('SELECT * FROM skus WHERE id = ?', false, false, [$id]);
}

print_r(QueryLog::stats());          // count, total_ms, max_ms, slow_count
print_r(QueryLog::detectNPlusOne(3)); // statements run more than 3 times, with their count

QueryLog::slowQueries(50) returns the statements that took 50 ms or more, and QueryLog::all() every statement with its duration.

The REPL

#

php taphra tinker opens a PsySH shell with the application booted: every framework and app class, config(), getContainer() and your DataStores are at hand. PsySH is not installed with the framework:

Shell
composer require --dev psy/psysh
php taphra tinker

In 1.0 the shell prints a Cannot redeclare config() error as it starts. The error is harmless and config() works, but the ds() shortcut the start-up banner mentions is not defined.