A Small Log Redaction Helper for Laravel (With Tests)
Logs are where secrets go to be forgotten. A failed HTTP call logs its URL, and the URL has a token in the query string. An exception message includes the response body. Someone logs the whole request to debug a webhook, and the signature header goes with it. Months later the log is in a backup, a support ticket and a monitoring service, and nobody remembers that it contains live credentials.
The best fix is not to log secrets. The second best is a safety net that masks the ones that slip through. This guide builds that safety net for Laravel as a small, tested log processor, and is explicit about what it cannot catch.
What this article is, and is not
The code ran on Laravel 13 and PHP 8.3 with 7 automated tests (25 assertions), including a test that writes through a real log channel to a file and reads it back. It is a safety net with precise rules, not a guarantee. It masks secrets that are named (a password key, a bearer token, a ?token= parameter) and cannot recognise a secret that appears as a bare string with no name around it. I did not measure its performance cost. Review what your own application logs, and treat this as the second line of defence.
Design: precise rules beat clever guessing
It is tempting to mask anything that looks like a long random string. That also masks request ids, hashes and file checksums, and the logs become useless. The helper takes the opposite approach and masks only values it can tie to a sensitive name:
- Keys in the context array, at any depth, compared case-insensitively with hyphens and underscores treated alike.
- Bearer and Basic credentials in text.
name=value pairs in query strings and form bodies.
"name": "value" pairs inside JSON text.
- Header lines such as
Authorization: ... and X-Webhook-Secret: ....
- Exceptions, converted to text so the message and trace stay, with the secrets removed.
A key counts as sensitive if it is exactly one of the listed names, or ends with _ plus one of them, such as stripe_secret or db_password. That is why input_tokens and max_tokens, which a model-API client may log on purpose, are left alone while token and access_token are masked.
The code
app/Logging/Redactor.php
<?php
namespace App\Logging;
use Throwable;
/** Masks secrets in log messages and context. Prefers precise rules over clever guessing. */
final class Redactor
{
public const MASK = '[REDACTED]';
/** Keys whose values are always masked (compared case-insensitively, with - and _ treated alike). */
private const KEYS = ['password', 'passwd', 'secret', 'token', 'api_key', 'apikey', 'authorization', 'cookie', 'set_cookie', 'client_secret', 'access_token', 'refresh_token', 'x_webhook_secret'];
public static function value(mixed $value): mixed
{
if (is_string($value)) {
return self::text($value);
}
if ($value instanceof Throwable) {
return get_class($value).': '.self::text((string) $value); // the full text, with trace, redacted
}
if (is_array($value)) {
$out = [];
foreach ($value as $key => $item) {
$out[$key] = is_string($key) && self::sensitiveKey($key) ? self::MASK : self::value($item);
}
return $out;
}
return $value;
}
public static function text(string $text): string
{
// "Authorization: Bearer abc" and bare "Bearer abc"
$text = preg_replace('/\b(Bearer|Basic)\s+[A-Za-z0-9\-._~+\/]+=*/i', '$1 '.self::MASK, $text);
// name=value pairs in query strings and form bodies
$text = preg_replace_callback('/([?&;\s])([A-Za-z0-9_\-]+)=([^&\s"\']*)/', function ($m) {
return self::sensitiveKey($m[2]) ? $m[1].$m[2].'='.self::MASK : $m[0];
}, $text);
// "name": "value" pairs inside JSON text
$text = preg_replace_callback('/"([A-Za-z0-9_\-]+)"\s*:\s*"((?:[^"\\\\]|\\\\.)*)"/', function ($m) {
return self::sensitiveKey($m[1]) ? '"'.$m[1].'":"'.self::MASK.'"' : $m[0];
}, $text);
// "Name: value" header lines
return preg_replace_callback('/^([A-Za-z\-]+):\s*(.+)$/m', function ($m) {
return self::sensitiveKey($m[1]) ? $m[1].': '.self::MASK : $m[0];
}, $text);
}
public static function sensitiveKey(string $key): bool
{
$k = strtolower(str_replace('-', '_', $key));
// Exact names, or a name that ENDS with one of them (stripe_secret, db_password). "input_tokens" and "max_tokens" do not qualify.
foreach (self::KEYS as $name) {
if ($k === $name || str_ends_with($k, '_'.$name)) {
return true;
}
}
return false;
}
}
app/Logging/RedactingProcessor.php
<?php
namespace App\Logging;
use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;
final class RedactingProcessor implements ProcessorInterface
{
public function __invoke(LogRecord $record): LogRecord
{
return $record->with(
message: Redactor::text($record->message),
context: Redactor::value($record->context),
extra: Redactor::value($record->extra),
);
}
}
app/Logging/RedactSecrets.php
<?php
namespace App\Logging;
use Illuminate\Log\Logger;
/** Use it as a "tap" on a log channel in config/logging.php. */
final class RedactSecrets
{
public function __invoke(Logger $logger): void
{
foreach ($logger->getLogger()->getHandlers() as $handler) {
$handler->pushProcessor(new RedactingProcessor);
}
}
}
Attach it to a channel with a tap in config/logging.php:
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'tap' => [App\Logging\RedactSecrets::class],
],
If you log through the stack channel, put the tap on each channel in the stack, or on the one you use. Every handler on that channel gets the processor, so the masking happens before anything is written.
What the tests check
| Test | What it protects against |
|---|
| Sensitive keys are masked at any depth, in any case | A password or key buried in a nested array |
| Bearer tokens and header lines are masked in text, other headers are kept | Logging a whole request including its credentials |
| Sensitive query parameters are masked, the others are kept | Tokens in URLs, which end up in logs and error messages |
| Sensitive values inside JSON text are masked, the rest is kept | A logged request or response body |
input_tokens, max_tokens, a UUID, "not a secret recipe" and "token count" are left alone | False positives that make logs useless |
| An exception message containing a URL token is masked, and the class and trace remain | Secrets leaking through error handling |
| A real log channel writes a file with the secrets removed and the useful fields kept | A processor that works in a unit test but is never wired in |
A taste of the end-to-end test, which is the one that matters most:
config(['logging.channels.redacted' => [
'driver' => 'single', 'path' => $file, 'tap' => [RedactSecrets::class], 'level' => 'debug',
]]);
Log::channel('redacted')->info('Calling https://api.test/x?token=abc123 with Authorization: Bearer zzz999', [
'password' => 'hunter2', 'order_id' => 4821, 'input_tokens' => 120,
]);
$written = file_get_contents($file);
expect($written)->not->toContain('abc123')->not->toContain('zzz999')->not->toContain('hunter2')
->toContain('4821')->toContain('"input_tokens":120')->toContain('[REDACTED]');
What it cannot catch
- A bare secret with no name around it, such as a log line that is only a token. Nothing ties it to a sensitive key.
- Secrets under names you did not list. Add the names your application uses, such as an internal
x_api_auth header.
- Personal data. Email addresses, names and addresses are not secrets in this sense and are not masked. Decide separately what personal data you may log.
- Anything logged before the tap runs or outside Laravel's logger, such as output sent to the web server's error log or a third-party service.
- Request and response bodies from HTTP clients and error pages, which can contain secrets in a format this does not recognise.
- Secrets that are in your code or files and never reach a log.
Better than masking: do not log it
- Log identifiers and outcomes, not payloads: the run id, the status and the duration.
- Never log request headers wholesale.
- Keep secrets out of URLs. Query strings are logged by servers, proxies and clients. Use headers.
- Check what your HTTP client logs and what your exceptions contain when a call fails.
- Treat stored logs as sensitive, with limited access and a retention period.
Common mistakes
- Masking by pattern alone and then having unreadable logs.
- Adding the processor but not testing the real channel.
- Forgetting exceptions, which often carry the URL and the body.
- Assuming it makes logging payloads safe. It does not.
- Logging secrets while debugging "just once" and leaving the line in.
Frequently asked questions
Does Laravel already hide sensitive input?
Laravel has a list of input fields that are not flashed back into forms after a validation error. That is a different mechanism and does not clean logs.
Will it slow my application down?
It runs a few regular expressions per log record. I did not measure the cost, so test it if you log at high volume.
Can I use this for other channels, such as a monitoring service?
Any channel that goes through Laravel's logger can use the tap. Check the service's own documentation for what it collects outside of logs.
What if I need to see a masked value while debugging?
Look it up from the source (the database or the provider's dashboard), or log a short hash of the value so you can tell two values apart without revealing them.
Where this fits
This is part of the pre-launch review in my Laravel security checklist. If you want your application's logging and secrets handling reviewed, see Laravel & PHP Development, or describe your application here. More utilities are collected under Developer Tools.