laravel-http-lens maintained by afsunday
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
- Requirements
- Installation
- What each row contains
- Configuration
- Extractors
- Guzzle
- Dashboard
- Delete old logs
- Troubleshooting
- Moving from farayaz/laravel-spy
- Update the package
- Contributing
- License
Features
Log what you need
- Log every request, or only the domains you choose, such as
api.example.comor*.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.
-
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" } ] -
Install the package, then publish its config and migrations:
composer require afsunday/laravel-http-lens php artisan vendor:publish --provider="Afsunday\HttpLens\HttpLensServiceProvider" -
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.
-
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 inHTTPLENS_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.
tokenhidesToken, but notmy_token. - Setting
HTTPLENS_OBFUSCATESreplaces the default list. Include everything you still want hidden, such asauthorization. The default list is inconfig/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
obfuscatesare 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
obfuscatesfor 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
--urlon its own still only deletes logs older thanHTTPLENS_CLEAN_DAYS.0days turns off the age check.--days=0orHTTPLENS_CLEAN_DAYS=0deletes 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:
HTTPLENS_ENABLEDistrue.- You have published and run the migrations.
- The app can connect to the database used for the logs.
- The request's domain is in
HTTPLENS_DOMAINS. An empty value logs nothing. - The URL does not contain anything in
HTTPLENS_EXCLUDE_URLS. - The request was not sent inside a database transaction that was rolled back. See Database.
- 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_bodyhas the reason, such ascURL error 28for a timeout orcURL error 7when 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 withHttpLens::handlerStack(). - A client from Laravel's container is only logged when
HTTPLENS_GUZZLE_ENABLEDistrue, unless it was created withHttpLens::handlerStack(). - If your app or another package sets up its own
Clientin the container, create that client withHttpLens::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_LENGTHandHTTPLENS_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 inHTTPLENS_REQUEST_BODY_EXCLUDE_CONTENT_TYPESorHTTPLENS_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, seeHTTPLENS_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
- Check that
HTTPLENS_DASHBOARD_ENABLEDistrue. - Check the address. It is
/httplens, unless you changedHTTPLENS_DASHBOARD_PREFIX. - Check that
HTTPLENS_DASHBOARD_MIDDLEWARElets you in. For most apps, it must includewebso that Laravel can tell you are signed in. - If your app caches its routes, run
php artisan route:cacheagain.
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.
-
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 -
Move your settings:
- In every
.envfile, including on your servers, changeSPY_at the start of each setting toHTTPLENS_. - Copy any changes you made in
config/spy.phptoconfig/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_OBFUSCATESreplaces the new, longer default list, so add any fields you want from it.
- In every
-
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')orconfig('spy.db_connection')config('httplens.db_connection')If your table does not have a
duration_mscolumn, add it with a new migration. -
Update your code:
Replace With Farayaz\LaravelSpy\LaravelSpyAfsunday\HttpLens\HttpLensAny other Farayaz\LaravelSpyAfsunday\HttpLensLaravelSpy::HttpLens::LaravelSpyServiceProviderHttpLensServiceProviderconfig('spy.config('httplens.spy_csv(andspy_rule_map(httplens_csv(andhttplens_rule_map(spy:cleanhttplens:clean. Add--forceif it is scheduledRoute names that start with spy.The same names, starting with httplens.The dashboard moves from
/spyto/httplens. To keep the old address, setHTTPLENS_DASHBOARD_PREFIX=spy. If you changed its views, publish the new views and make your changes again. -
Delete
config/spy.php, then remove the original.config/spy.phpuses the original's helper functions, soartisanfails if you remove the original first. Keeping both packages would log every request twice.php artisan config:clear composer remove farayaz/laravel-spy -
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
-
Fork the repository and clone your fork.
-
Create a branch for your change.
-
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.