# Shipping Laravel logs over HTTP without slowing your requests

To send Laravel logs to a remote service without making requests slower, buffer the records in your Monolog handler, send them as one batch after the response has gone out, cap each batch by size and age, flush explicitly in long-running workers, and never let a failed send throw into your app. Here is why each of those rules exists in our own package, including the one we got wrong.

## One HTTP call per log line is a trap

The simplest handler does a POST inside `write()`. Every `Log::info()` becomes a network round trip, so a request that logs twenty lines makes twenty HTTP calls before the user gets a byte back. It's easy to miss when you test with one log line, which is why ours buffered from the first commit.

## Buffer, then send once after the response

Now the handler only appends to an array in `write()` and registers a shutdown function the first time it sees a record:

```php
protected function write(LogRecord $record): void
{
    $this->buffer[] = $this->normalize($record);

    if (! $this->shutdownRegistered) {
        $this->shutdownRegistered = true;
        register_shutdown_function(fn () => $this->flush());
    }

    if (count($this->buffer) >= $this->batchSize) {
        $this->flush();
    }
}
```

Under PHP-FPM this costs the user nothing. Laravel sends the response through Symfony's `Response::send()`, which calls `fastcgi_finish_request()`, so by the time shutdown functions run the browser already has the page. That does not hold for `php artisan serve` or mod_php, so don't benchmark it there and conclude it is slow.

## Cap the batch by size and by age

A long artisan command can log thousands of lines. Holding all of them until the process exits wastes memory and delivers everything in one lump at the end. We send when the buffer reaches 50 records or its oldest record is 2 seconds old, whichever comes first. Memory stays flat and the logs arrive while the command is still running.

## Workers never shut down

This is the one that bit us. `queue:work`, Horizon and Octane keep a single process alive for hours, so a shutdown function does not run between jobs, and an age check that only runs on the next `write()` never fires if the worker goes quiet. A job that logs three lines can leave them sitting in memory until the next job happens to log something.

The fix is to flush on the framework's own lifecycle events: `JobProcessed`, `JobFailed` and `WorkerStopping` for queue workers, and `RequestTerminated` for Octane. If you write your own handler, add these listeners from the start. Our package does this since v0.1.8.

## The logger must never take down the app

If the logging service is down or slow, your checkout should not be. Every send has a short curl timeout, is wrapped in a `try`/`catch`, and on failure writes one line to PHP's `error_log()` instead:

```php
try {
    self::send($this->endpoint, $this->token, $batch, $this->httpTimeout);
} catch (Throwable $e) {
    error_log('[tailcove] failed to send log batch: '.$e->getMessage());
}
```

The same goes for anything that enriches records. A processor that adds the user id must not throw when there is no authenticated user or no database connection.

## Keep the message constant, put the details in context

```php
// Hard to search and impossible to count
Log::info("Order {$order->id} placed for {$order->total}");

// One event, with fields you can filter and alert on
Log::info('Order placed', ['order_id' => $order->id, 'total_cents' => $order->total]);
```

With a constant message, every occurrence is the same event, so you can count it, chart it and alert when it stops happening. Our [structured logging guide](https://tailcove.dev/blog/structured-logging-a-practical-guide) goes further into which fields are worth adding.

## Workers read their own environment

A common reason logs from jobs never show up is a token that is set for the web container but not for the queue worker or Horizon. If web requests log fine and jobs don't, check the worker's environment before anything else.

## Or skip the remote call in the request entirely

If you already run Redis queues, you can dispatch each batch as a job instead of sending it from the shutdown function. The request then only pushes to Redis, and the queue's own retry and backoff handle a delivery failure. Our package does this with `TAILCOVE_DISPATCH=queue`.

## Try it

All of the above is what the `tailcove/laravel` package does, and its source is MIT on [GitHub](https://github.com/tailcove/laravel). The [Laravel logging guide](https://tailcove.dev/guides/laravel-logging) gets you from `composer require` to a live tail in about ten minutes, and the [package reference](https://tailcove.dev/docs/sending-logs/laravel-package) lists every option.
