PHPackages                             dineshrao/log-sanitizer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. dineshrao/log-sanitizer

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

dineshrao/log-sanitizer
=======================

A lightweight Monolog processor to automatically redact PII and sensitive data from logs.

00PHPCI passing

Since Jun 26Pushed todayCompare

[ Source](https://github.com/dineshrao275/log-sanitizer)[ Packagist](https://packagist.org/packages/dineshrao/log-sanitizer)[ RSS](/packages/dineshrao-log-sanitizer/feed)WikiDiscussions main Synced today

READMEChangelogDependenciesVersions (2)Used By (0)

log-sanitizer
=============

[](#log-sanitizer)

A lightweight, zero-config Monolog processor that automatically redacts PII and sensitive data (passwords, tokens, emails, credit cards) from your PHP application logs. GDPR-friendly.

Installation
------------

[](#installation)

```
composer require dineshrao/log-sanitizer
```

Requirements
------------

[](#requirements)

- PHP 8.2+
- monolog/monolog ^3.0

Quick Start
-----------

[](#quick-start)

```
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Dineshrao\LogSanitizer\PiiSanitizerProcessor;

$log = new Logger('app');
$log->pushHandler(new StreamHandler('app.log', \Monolog\Level::Debug));
$log->pushProcessor(new PiiSanitizerProcessor());

$log->info('User login', [
    'username' => 'dinesh',
    'password' => 'secret123',
]);
// password → [REDACTED]
```

Configuration
-------------

[](#configuration)

### Legacy constructor

[](#legacy-constructor)

```
$processor = new PiiSanitizerProcessor(
    customKeys:        ['otp', 'pin'],
    mask:              '***',
    redactEmails:      true,
    redactCreditCards: true
);
```

ParameterTypeDefaultDescription`customKeys``array``[]`Additional key names to redact beyond defaults`mask``string``'[REDACTED]'`Replacement string for redacted values`redactEmails``bool``true`Scan string values for email patterns`redactCreditCards``bool``true`Scan string values for credit card numbers (Luhn-validated)### SanitizerConfig (recommended for advanced use)

[](#sanitizerconfig-recommended-for-advanced-use)

```
use Dineshrao\LogSanitizer\SanitizerConfig;

$config = SanitizerConfig::default()
    ->withCustomKeys(['otp', 'pin'])
    ->withMask('***')
    ->withoutEmailRedaction()
    ->withoutCreditCardRedaction()
    ->withMatchMode('contains')
    ->withExceptKeys(['email_template'])
    ->withPartialMasking();

$processor = new PiiSanitizerProcessor($config);
```

MethodDefaultDescription`withCustomKeys(array)``[]`Additional key names to redact`withMask(string)``'[REDACTED]'`Replacement string`withPartialMasking()``false`Show partial values instead of full mask`withFullMasking()``true`Full mask replacement (default)`withMatchMode('exact''contains')``'exact'``withExceptKeys(array)``[]`Keys to exclude from redaction`withEmailRedaction()``true`Enable email pattern scanning`withoutEmailRedaction()`-Disable email pattern scanning`withCreditCardRedaction()``true`Enable credit card pattern scanning`withoutCreditCardRedaction()`-Disable credit card pattern scanningKey Match Modes
---------------

[](#key-match-modes)

### Exact mode (default)

[](#exact-mode-default)

Only keys that exactly match a sensitive key are redacted:

```
'password' => 'secret'   // redacted
'user_password' => 'x'   // not redacted
```

### Contains mode

[](#contains-mode)

Any key containing a sensitive word is redacted:

```
$config = SanitizerConfig::default()->withMatchMode('contains');

'user_password'   => 'secret'  // redacted (contains "password")
'jwt_token'       => 'abc'     // redacted (contains "token")
'stripe_api_key'  => 'sk_...'  // redacted (contains "api_key")
'my_password_reset' => '...'   // redacted (contains "password")
```

### Combining with exceptKeys

[](#combining-with-exceptkeys)

```
$config = SanitizerConfig::default()
    ->withMatchMode('contains')
    ->withExceptKeys(['email_template']);
```

Key Normalization
-----------------

[](#key-normalization)

Key names are normalized to snake\_case for consistent matching. This means `apiKey`, `api-key`, `api_key`, and `API_KEY` are all treated identically:

```
$processor = new PiiSanitizerProcessor();

'apiKey'       => 'secret'  // redacted (normalizes to "api_key")
'api-key'      => 'secret'  // redacted (normalizes to "api_key")
'API_KEY'      => 'secret'  // redacted (normalizes to "api_key")
'clientSecret' => 'secret'  // redacted (normalizes to "client_secret")
```

Masking Modes
-------------

[](#masking-modes)

### Full masking (default)

[](#full-masking-default)

All matching values are replaced with the configured mask string:

```
['password' => 'mySecretPass!'] → ['password' => '[REDACTED]']
['email'    => 'dinesh@example.com'] → ['email' => '[REDACTED]']
```

### Partial masking

[](#partial-masking)

Show enough context for debugging while protecting sensitive data:

```
$config = SanitizerConfig::default()->withPartialMasking();

// Sensitive keys
['password' => 'mySecretPass!'] → ['password' => 'my*********s!']
['email'    => 'dinesh@example.com'] → ['email' => 'd*****@example.com']

// Pattern redaction within values
['note' => 'Contact dinesh@example.com'] → ['note' => 'Contact d*****@example.com']
['note' => 'Card: 4111111111111111']    → ['note' => 'Card: ************1111']
['note' => 'Card: 4111-1111-1111-1111'] → ['note' => 'Card: ****-****-****-1111']
```

Non-string values are always fully masked regardless of mode:

```
['password' => 123456] → ['password' => '[REDACTED]']
['secret' => true]     → ['secret' => '[REDACTED]']
```

Default Redacted Keys
---------------------

[](#default-redacted-keys)

CategoryKeysAuthentication`password`, `password_confirmation`, `secret`, `token`, `api_key`, `auth_key`, `access_token`, `refresh_token`, `authorization`, `bearer`, `jwt`, `id_token`, `csrf_token`, `session`, `session_id`Financial`cvv`, `cc_number`, `card_number`, `pin`, `passcode`Personal`ssn`, `social_security`, `email`, `phone`, `otp`Infrastructure`private_key`, `client_secret`Session`cookie`, `set_cookie`Pattern Redaction
-----------------

[](#pattern-redaction)

String values are scanned for patterns even when the key is not in the sensitive list:

- **Emails**: Matches `user@example.com`, `user+tag@example.com`, etc.
- **Credit cards**: Validated with the Luhn algorithm to reduce false positives. Supports `4111111111111111`, `4111-1111-1111-1111`, and `4111 1111 1111 1111` formats.

### Disable pattern redaction

[](#disable-pattern-redaction)

```
$processor = new PiiSanitizerProcessor(
    redactEmails: false,
    redactCreditCards: false
);
```

Custom Keys
-----------

[](#custom-keys)

```
$processor = new PiiSanitizerProcessor(
    customKeys: ['otp', 'pin', 'verification_code']
);
```

Masking Behavior
----------------

[](#masking-behavior)

Sensitive keys are redacted regardless of value type:

```
['password' => 123456]     → ['password' => '[REDACTED]']
['secret' => true]         → ['secret' => '[REDACTED]']
['token' => null]          → ['token' => '[REDACTED]']
```

Non-sensitive non-string values are left untouched:

```
['user_id' => 7, 'is_active' => true, 'last_login' => null]
// unchanged
```

Nested arrays are sanitized recursively:

```
[
    'user' => [
        'credentials' => ['password' => 'secret']
    ]
]
// → user.credentials.password → [REDACTED]
```

Security Notes
--------------

[](#security-notes)

This package reduces accidental PII logging but should not replace avoiding sensitive logging at source. Always follow least-privilege logging practices.

Framework Examples
------------------

[](#framework-examples)

### Laravel

[](#laravel)

```
// config/logging.php
use Dineshrao\LogSanitizer\PiiSanitizerProcessor;

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['single'],
    ],
    'single' => [
        'driver' => 'single',
        'path' => storage_path('logs/laravel.log'),
        'tap' => [App\Logging\SanitizeLog::class],
    ],
],
```

```
// app/Logging/SanitizeLog.php
namespace App\Logging;

use Dineshrao\LogSanitizer\PiiSanitizerProcessor;
use Monolog\Logger;

class SanitizeLog
{
    public function __invoke(Logger $logger): void
    {
        $logger->pushProcessor(new PiiSanitizerProcessor());
    }
}
```

### Symfony

[](#symfony)

```
# config/services.yaml
services:
    Dineshrao\LogSanitizer\PiiSanitizerProcessor:
        arguments:
            $customKeys: ['otp']
            $redactCreditCards: true

    monolog.processor.pii_sanitizer:
        tags:
            - { name: monolog.processor }
```

Testing
-------

[](#testing)

```
vendor/bin/phpunit
```

License
-------

[](#license)

MIT

###  Health Score

21

—

LowBetter than 18% of packages

Maintenance65

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/95177229?v=4)[Dinesh Rao](/maintainers/dineshrao275)[@dineshrao275](https://github.com/dineshrao275)

---

Top Contributors

[![dineshrao275](https://avatars.githubusercontent.com/u/95177229?v=4)](https://github.com/dineshrao275 "dineshrao275 (7 commits)")

### Embed Badge

![Health badge](/badges/dineshrao-log-sanitizer/health.svg)

```
[![Health](https://phpackages.com/badges/dineshrao-log-sanitizer/health.svg)](https://phpackages.com/packages/dineshrao-log-sanitizer)
```

###  Alternatives

[psr/log

Common interface for logging libraries

10.4k1.2B10.9k](/packages/psr-log)[open-telemetry/api

API for OpenTelemetry PHP.

1938.5M261](/packages/open-telemetry-api)[open-telemetry/sdk

SDK for OpenTelemetry PHP.

2326.5M315](/packages/open-telemetry-sdk)[illuminated/console-logger

Logging and Notifications for Laravel Console Commands.

8676.7k](/packages/illuminated-console-logger)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
