Looking to hire Laravel developers? Try LaraJobs

laravel-http-lens maintained by afsunday

Description
Log outgoing HTTP requests from Laravel, for every domain or only the ones you choose.
Last update
2026/12/02 00:06 (dev-our-version)
License
Links
Downloads
5

Comments
comments powered by Disqus

Laravel HTTP Lens

See what your Laravel app sends to other services, and what comes back.

Laravel HTTP Lens saves your app's outgoing HTTP requests and their results in your database, including timeouts and refused connections. When a call to a bank, courier or other API fails, you can see what was sent, what came back and how long it took.

Contents

Features

Log what you need

  • Log every request, or only the domains you choose, such as api.example.com or *.example.org.
  • Leave out any URLs you do not want to log.
  • Use it with Laravel's HTTP client and supported Guzzle clients.

Find out what went wrong

  • See the URL, method, headers, bodies, status and time taken.
  • See timeouts and refused connections, with the reason they failed.
  • See each retry made by Laravel's HTTP client in its own row.
  • See requests that never finished, because each row is saved before its request is sent.

Protect secrets

  • Hide passwords, tokens and other named fields in headers, URL queries, JSON, XML, form data and error messages.
  • Give a domain its own extractor, a small class that decides what is saved from its bodies. It can also read XML sent as text inside SOAP.
  • File uploads and binary files are not saved, unless the domain has an extractor.
  • If a body cannot be read or its secrets cannot be hidden, a note is saved instead.

Some secrets cannot be found by name. See Hide secrets before you log a new API in production.

Keep your app working

  • A logging error does not stop your request or change its reply.
  • Streamed, read-once and oversized bodies are not read.
  • Your app's own Guzzle client is not replaced.

Manage your logs

  • Search and filter logs in an optional dashboard with charts.
  • Delete old logs with httplens:clean.
  • Choose the table and database connection.

Requirements

  • PHP 8.1 or newer
  • Laravel 10, 11, 12 or 13

Installation

If your app already uses farayaz/laravel-spy, follow these steps instead.

  1. The package is not on Packagist, so add its Git repository to your app's composer.json:

    "repositories": [
        { "type": "vcs", "url": "https://github.com/afsunday/laravel-http-lens" }
    ]
    
  2. Install the package, then publish its config and migrations:

    composer require afsunday/laravel-http-lens
    php artisan vendor:publish --provider="Afsunday\HttpLens\HttpLensServiceProvider"
    
  3. To use a different table or database connection, set it now, before you create the table. Use a separate connection if your app sends requests inside database transactions. Otherwise, a rollback also removes their logs.

  4. Create the table:

    php artisan migrate
    

Requests are now logged. To check, send one and look for a new row in the http_logs table:

use Illuminate\Support\Facades\Http;

Http::get('https://example.com');

Old logs are only deleted when httplens:clean runs, so schedule it.

What each row contains

Column Value
url, method Where the request was sent, and its HTTP method
request_headers, request_body What was sent
status The result. See the next table
duration_ms How long it took, in milliseconds
response_headers, response_body The reply, or the error message in response_body when status is 0
status Meaning
HTTP code A full reply arrived, including 4xx and 5xx errors
0 The request failed before a full reply arrived, such as a timeout
Empty The request did not finish, or its result could not be saved

Configuration

The settings are in config/httplens.php, which you published during installation. To publish only the config:

php artisan vendor:publish --provider="Afsunday\HttpLens\HttpLensServiceProvider" --tag=config

Most settings can also be changed in .env. If you cache your config, run php artisan config:cache after changing it.

Turn logging on or off

HTTPLENS_ENABLED=true
HTTPLENS_GUZZLE_ENABLED=true
  • HTTPLENS_ENABLED: turns all logging on or off.
  • HTTPLENS_GUZZLE_ENABLED: also logs the Guzzle client that Laravel creates, unless your app has its own. See Guzzle.

Domains

HTTPLENS_DOMAINS=api.example.com,*.example.org
Value What is logged
* Every request. This is the default.
api.example.com Only that domain, not its subdomains
*.example.org Its subdomains, such as eu.example.org, but not example.org itself
Empty (HTTPLENS_DOMAINS=) Nothing

Separate domains with commas. A full URL works too, but only its domain is used. The port and path are ignored. Similar names, such as api.example.com.attacker.test, do not match.

URLs to leave out

HTTPLENS_EXCLUDE_URLS=api/health,ping,status

A URL containing any of these is not logged, even when its domain is in HTTPLENS_DOMAINS.

Hide secrets

HTTPLENS_OBFUSCATES='*:authorization,cookie,password,token|api.example.com:account|*.example.org:key,code'
HTTPLENS_OBFUSCATION_MASK=***
  • * applies to every domain. Other rules also apply to the domains they name, which work the same way as in HTTPLENS_DOMAINS.
  • Separate fields with commas and rules with |. To give several domains the same rule, separate them with commas: domain1.com,domain2.com:key.
  • Names must match in full, but capital letters do not matter. token hides Token, but not my_token.
  • Setting HTTPLENS_OBFUSCATES replaces the default list. Include everything you still want hidden, such as authorization. The default list is in config/httplens.php.

Values are hidden in headers, URL queries, JSON, XML (including XML sent as text inside XML), form data and error messages. A username and password before the domain in a URL are always hidden.

Values are found by the name next to them. The normal rules cannot find:

  • a secret with no name, such as a token in the URL path. Leave those URLs out with HTTPLENS_EXCLUDE_URLS.
  • a name and value in separate fields, such as {"name": "password", "value": "..."}. Use an extractor.
  • every part of an unquoted value that contains spaces, such as password: two words. Use an extractor.

Before you log a new API in production, check a test request and make sure its secrets are hidden.

Bodies that are not saved

The row is still saved, with a note in place of the body, for:

  • file uploads (multipart/form-data), images, PDFs and other binary files, unless the domain has an extractor
  • streamed bodies, because reading them could take them away from your app
  • bodies larger than HTTPLENS_MAX_BODY_SIZE
  • content types you exclude:
HTTPLENS_REQUEST_BODY_EXCLUDE_CONTENT_TYPES=text/csv
HTTPLENS_RESPONSE_BODY_EXCLUDE_CONTENT_TYPES=text/html,text/csv

Limits

HTTPLENS_MAX_BODY_SIZE=1048576
HTTPLENS_FIELD_MAX_LENGTH=10000
HTTPLENS_FIELD_MAX_ROWS=10000
  • HTTPLENS_MAX_BODY_SIZE: the largest body to read, in bytes. The default is 1 MB.
  • HTTPLENS_FIELD_MAX_LENGTH: the most characters to save for each value. Longer values are cut after their secrets are hidden.
  • HTTPLENS_FIELD_MAX_ROWS: the most items to save for each array.

Database

HTTPLENS_TABLE_NAME=http_logs
HTTPLENS_DB_CONNECTION=

Set both before you run the migrations, because the migrations use them.

If your app sends requests inside a database transaction, give the logs their own connection. Otherwise, if the transaction is rolled back, its log rows are removed too. That often happens when the request fails. On PostgreSQL, a failed log insert can also stop the rest of your transaction.

In config/database.php, copy your main connection under a new name, such as httplens. It can use the same database. Then set HTTPLENS_DB_CONNECTION=httplens.

Extractors

An extractor decides what is saved from one domain's request and response bodies. Use one when:

  • the body needs to be read in a special way, such as XML sent as text inside XML
  • you only want to save part of it
  • secrets are somewhere the normal rules cannot find them

Domains without an extractor are read and hidden in the normal way.

Create an extractor

Extend Extractor and return what should be saved: text, an array or null.

namespace App\HttpLens;

use Afsunday\HttpLens\Extractor;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class ExampleExtractor extends Extractor
{
    public function request(string $body, RequestInterface $request): mixed
    {
        return ['path' => $request->getUri()->getPath()];
    }

    public function response(string $body, ResponseInterface $response, RequestInterface $request): mixed
    {
        $reply = json_decode($body, true);

        return ['id' => $reply['id'] ?? null, 'message' => $reply['message'] ?? null];
    }
}

Both methods are optional. If you leave one out, that body is read in the normal way. Keep the method parameters exactly as shown, or PHP will not load the class.

Then add it to config/httplens.php:

'extractors' => [
    'api.example.com' => App\HttpLens\ExampleExtractor::class,
    '*.example.org' => App\HttpLens\OtherExtractor::class,
],

Domains work the same way as in HTTPLENS_DOMAINS. The first match is used, so put exact domains above *. ones. An extractor does not turn on logging for its domain. The domain must also be allowed by HTTPLENS_DOMAINS.

Example: a SOAP API with a login inside the XML

Some banks send XML as text inside a SOAP message. xml() makes it readable and hides the tags you name, whatever their prefix:

class BankExtractor extends Extractor
{
    public function request(string $body, RequestInterface $request): mixed
    {
        return $this->xml($body, ['clientid', 'username', 'password']);
    }

    public function response(string $body, ResponseInterface $response, RequestInterface $request): mixed
    {
        return $this->xml($body);
    }
}

The log shows the login tags as <password>***</password>. The reply's <Code> and <Message> stay readable, so you can see errors sent with status 200.

Good to know

  • Secrets are still hidden afterwards. The rules in obfuscates are applied to whatever the extractor returns.
  • If an extractor fails, the body is not saved. The row says so. The error report gives only the type and location of the error, because its message could contain the body.
  • Your request is not affected. Extractors get copies of the request and reply.
  • Requests sent by an extractor are not logged. Avoid sending any, because they slow down the real request.
  • Extractors only handle bodies. Use obfuscates for headers, URLs and error messages.
  • Extractors are not used for empty bodies, excluded content types, or bodies that are streamed or too large.
  • Extractors are created by Laravel, so they can use dependency injection.

Guzzle

Requests made with Laravel's HTTP client are always covered. For requests made directly with Guzzle, it depends on how the client is created:

Client Logged?
From Laravel's container, such as app(Client::class) Yes, unless your app or another package sets up its own client
Created with HttpLens::handlerStack() Yes
Created with a plain new Client() No

HTTPLENS_DOMAINS, extractors and the rules for hiding secrets work the same way for every logged client.

Clients from Laravel's container

These are logged by default:

HTTPLENS_GUZZLE_ENABLED=true
use GuzzleHttp\Client;

$client = app(Client::class);
$client->get('https://api.example.com');

Clients that Laravel passes to your classes are logged too:

use GuzzleHttp\Client;

class PaymentService
{
    public function __construct(protected Client $client) {}

    public function check()
    {
        return $this->client->get('https://api.example.com');
    }
}

If your app or another package sets up its own Client in the container, that one is used instead. To log it, create it with HttpLens::handlerStack().

Clients you create yourself

Use HttpLens::handlerStack() as the client's handler:

use Afsunday\HttpLens\HttpLens;
use GuzzleHttp\Client;

$client = new Client([
    'handler' => HttpLens::handlerStack(),
]);

$client->get('https://api.example.com');

This works whether HTTPLENS_GUZZLE_ENABLED is on or off. To log only the Guzzle clients you choose, turn it off:

HTTPLENS_GUZZLE_ENABLED=false

Requests made with Laravel's HTTP client are still logged.

Dashboard

The dashboard shows your logs and charts in the browser. It is off by default.

Enable dashboard

Logs can contain private data, so only let administrators in. Set the middleware before you turn the dashboard on:

HTTPLENS_DASHBOARD_MIDDLEWARE=web,auth,admin
HTTPLENS_DASHBOARD_ENABLED=true

Replace admin with your app's own administrator check, such as can:admin. This middleware protects every dashboard page. The default is only auth, which does not check for administrators.

Then open /httplens. To use a different address, set HTTPLENS_DASHBOARD_PREFIX:

HTTPLENS_DASHBOARD_PREFIX=admin/httplens

If your app caches its config or routes, refresh those caches after changing these settings.

Dashboard pages

Page What it shows
/httplens Analytics: request totals, requests over time, and the URLs with the most 5xx errors
/httplens/logs HTTP logs: a list you can search and filter

/httplens/analytics also opens Analytics.

  • Choose a period: the last 24 hours, 7 days, 30 days or all time. It applies to both pages.
  • Filter the logs by URL, method, status or minimum duration.
  • Find timeouts and refused connections by setting the status to Connection error. Analytics includes them in its total, but does not count them separately.
  • Sort the logs by newest or oldest, with 10, 20 or 50 on each page.
  • Click a URL to see its saved headers and bodies without leaving the list.

The chart script comes with the package, so the dashboard does not need a CDN or web fonts.

Change the design

Turn the dashboard on first, then copy its views to resources/views/vendor/httplens:

php artisan vendor:publish --tag=httplens-views

Laravel then uses your copies, so they do not get changes from later versions of this package.

Delete old logs

Logs are kept until you run httplens:clean. It deletes rows older than HTTPLENS_CLEAN_DAYS, which is 30 days by default:

HTTPLENS_CLEAN_DAYS=30

Run it yourself

# Delete logs older than HTTPLENS_CLEAN_DAYS
php artisan httplens:clean

# Delete logs older than 7 days
php artisan httplens:clean --days=7

# Delete logs older than 1 day whose URL contains "api/users"
php artisan httplens:clean --days=1 --url=api/users
  • --url on its own still only deletes logs older than HTTPLENS_CLEAN_DAYS.
  • 0 days turns off the age check. --days=0 or HTTPLENS_CLEAN_DAYS=0 deletes every log, or every log that matches --url.

In production, the command asks you to confirm first. Add --force to skip the question.

Run it every day

Include --force. A scheduled command cannot answer the question, so without --force nothing is deleted in production.

In Laravel 11 or newer, add this to routes/console.php:

use Illuminate\Support\Facades\Schedule;

Schedule::command('httplens:clean --force')->daily();

In Laravel 10, add it to the schedule method in app/Console/Kernel.php:

protected function schedule(Schedule $schedule): void
{
    $schedule->command('httplens:clean --force')->daily();
}

Laravel's scheduler must be running on your server.

Troubleshooting

If your app caches its config, run php artisan config:cache after changing any setting.

Nothing is logged

Check that:

  1. HTTPLENS_ENABLED is true.
  2. You have published and run the migrations.
  3. The app can connect to the database used for the logs.
  4. The request's domain is in HTTPLENS_DOMAINS. An empty value logs nothing.
  5. The URL does not contain anything in HTTPLENS_EXCLUDE_URLS.
  6. The request was not sent inside a database transaction that was rolled back. See Database.
  7. Your Laravel log has no database or Laravel HTTP Lens errors. Logging errors are reported there.

The status is 0 or empty

  • 0: the request failed before a full reply arrived. response_body has the reason, such as cURL error 28 for a timeout or cURL error 7 when it could not connect.
  • Empty: the request did not finish, or its result could not be saved. For example, PHP may have been stopped while it was waiting.

Laravel's HTTP client is logged, but Guzzle is not

  • A plain new Client() is never logged. Create it with HttpLens::handlerStack().
  • A client from Laravel's container is only logged when HTTPLENS_GUZZLE_ENABLED is true, unless it was created with HttpLens::handlerStack().
  • If your app or another package sets up its own Client in the container, create that client with HttpLens::handlerStack().

See Guzzle for examples.

A body is missing or has changed

  • Nothing was saved: the body was empty, or the domain's extractor returned nothing.
  • Only part was saved: check the domain's extractor. Long values and arrays are also cut to fit HTTPLENS_FIELD_MAX_LENGTH and HTTPLENS_FIELD_MAX_ROWS.
  • Some values show ***: their names are in your list of fields to hide. See Hide secrets.
  • content excluded by configuration: its content type is in HTTPLENS_REQUEST_BODY_EXCLUDE_CONTENT_TYPES or HTTPLENS_RESPONSE_BODY_EXCLUDE_CONTENT_TYPES.
  • Not saved: ...: the body was left out on purpose. The rest of the note says why:
    • binary or multipart content: use an extractor if you need part of it.
    • the body is streamed or too large: streamed bodies are never saved. For large ones, see HTTPLENS_MAX_BODY_SIZE.
    • the body could not be read: the extractor or the reader failed. The Laravel log shows where.
    • the sensitive values could not be hidden: the text was too complex to check safely.
    • the response could not be stored: the database rejected it. The status and duration were kept.

The dashboard does not open

  1. Check that HTTPLENS_DASHBOARD_ENABLED is true.
  2. Check the address. It is /httplens, unless you changed HTTPLENS_DASHBOARD_PREFIX.
  3. Check that HTTPLENS_DASHBOARD_MIDDLEWARE lets you in. For most apps, it must include web so that Laravel can tell you are signed in.
  4. If your app caches its routes, run php artisan route:cache again.

Moving from farayaz/laravel-spy

Both packages use the same table, so your existing logs are kept.

Your old settings do not carry over by themselves. Follow every step before you deploy. If you miss your own list of fields to hide, those secrets could be saved.

  1. Add the repository shown in Installation, then install this package before you remove the original. Publish only its config:

    composer require afsunday/laravel-http-lens
    php artisan vendor:publish --provider="Afsunday\HttpLens\HttpLensServiceProvider" --tag=config
    
  2. Move your settings:

    • In every .env file, including on your servers, change SPY_ at the start of each setting to HTTPLENS_.
    • Copy any changes you made in config/spy.php to config/httplens.php.
    • If you use your own table or database connection, check that both settings were moved.
    • Check your list of fields to hide. HTTPLENS_OBFUSCATES replaces the new, longer default list, so add any fields you want from it.
  3. Keep the migrations you already have. Do not publish this package's migrations or use vendor:publish --force, which overwrites your files. Migrations that have already run will not run again, but a new database still needs them. In your published migration files for this table:

    Replace With
    config('spy.table_name') config('httplens.table_name')
    config('spy.connection') or config('spy.db_connection') config('httplens.db_connection')

    If your table does not have a duration_ms column, add it with a new migration.

  4. Update your code:

    Replace With
    Farayaz\LaravelSpy\LaravelSpy Afsunday\HttpLens\HttpLens
    Any other Farayaz\LaravelSpy Afsunday\HttpLens
    LaravelSpy:: HttpLens::
    LaravelSpyServiceProvider HttpLensServiceProvider
    config('spy. config('httplens.
    spy_csv( and spy_rule_map( httplens_csv( and httplens_rule_map(
    spy:clean httplens:clean. Add --force if it is scheduled
    Route names that start with spy. The same names, starting with httplens.

    The dashboard moves from /spy to /httplens. To keep the old address, set HTTPLENS_DASHBOARD_PREFIX=spy. If you changed its views, publish the new views and make your changes again.

  5. Delete config/spy.php, then remove the original. config/spy.php uses the original's helper functions, so artisan fails if you remove the original first. Keeping both packages would log every request twice.

    php artisan config:clear
    composer remove farayaz/laravel-spy
    
  6. Send a test request. Check that it adds one row and that your secrets are hidden. If your app caches its config or routes, refresh those caches when you deploy.

What is different

Original This package
Logs every domain Logs every domain, or only those in HTTPLENS_DOMAINS
The same reader for every domain Each domain can have its own extractor
Rules for hiding secrets need the exact domain *.example.com works too
XML becomes an array, and SOAP can be lost XML is kept as text, with its secrets hidden
In plain text, replaces the word password Hides the value and keeps the word
Saves files and uploads as base64 Does not save them, unless the domain has an extractor
Hides password and token by default Also hides authorization headers, cookies, API keys, PINs and more
Uses 🫣 to hide values Uses ***
Always replaces Laravel's Guzzle client Keeps your app's own client if it has one
The migrations ignore the database connection setting The migrations use it

Update the package

composer update afsunday/laravel-http-lens

Then check vendor/afsunday/laravel-http-lens/config/httplens.php for new settings.

Contributing

Bug reports and pull requests are welcome.

Do not include real logins, API keys or customer data in code, tests, issues or pull requests. Check any log rows you share for them too.

Set up the project

  1. Fork the repository and clone your fork.

  2. Create a branch for your change.

  3. Install the packages:

    composer install
    

Check your change

vendor/bin/phpunit --no-progress
vendor/bin/pint --test   # check the code style
vendor/bin/pint          # fix the code style

See Testing for more about the tests.

Before you open a pull request

  • Keep it to one change.
  • Add or update tests when behaviour changes.
  • If you change how secrets are hidden, test what must be hidden and what must stay readable.
  • Update this README when you add or change a feature.

License

Laravel HTTP Lens by afsunday uses the MIT license. It is based on farayaz/laravel-spy v1.8.0.