Kevin Eaton

Packages · Open source

Laravel Log Containers

Wrap a block of code in a log container, and everything that happens inside it is logged together. You get what ran, how long it took, whether it finished, and the exception if it didn't. The code inside the block doesn't change.

Jobs that ran overnight with nothing to show for it but a log file. The only way to tell whether one had run was the modification time on the file.

Before

$order = ['id' => 42, 'total' => 80];

reserveStock($order);
chargeCard($order);
sendReceipt($order);

Here is the same code wrapped in a container. The container is passed into the closure, so you can log from inside the block as you go.

After

use Keaton\LogContainers\LogContainer;

OrderLog::doing('fulfilling order 42', function (LogContainer $log) use ($order): void {
    reserveStock($order);
    $log->info('Stock reserved');

    chargeCard($order);
    $log->info('Card charged', ['total' => $order['total']]);

    sendReceipt($order);
    $log->success('Receipt sent');
});
fulfilling order 42: completed, 3 entries
  info     Stock reserved
  info     Card charged
  success  Receipt sent

The block is stored as a session, a database row with a name, a status and a duration. Every entry is a row too, linked to its session, so you can query your logs and do not have to search a file. If the block throws, the session is marked failed and the exception is stored. Then it is thrown again, so your own error handling still runs. The package is meant for work you want to look at later. For everything else, Log::info() is still the right tool.

What it does

  • doing() names the work and times it. during() names what was going on around it, like a checkout, a nightly import or a webhook. Both put their label on every entry written inside them, and they nest, so an entry reads "checkout > validating cart: Cart is valid".
  • Code that is called from inside a block joins it with a plain OrderLog::info(), and a block inside a block is stored as its child session, so you can follow a run from the top down.
  • The labels are columns. You can list entries by step, by situation or by session with a query.
  • tagWith($order) links entries to an Eloquent model, so you can list everything that happened to a record.
  • Every entry stores an execution id, which ties together the entries of one request, job or command across containers.
  • A container can redact secrets from the context, limit how many entries it keeps and delete old ones.
  • A watch is a small class that fires an event when an entry you care about is written.
  • You do not need a block. OrderLog::info('Order placed', ['order_id' => 42]) stores one entry.
  • LogContainers::fake() and a few assertions for your tests.

Next packageLaravel Hash List