PHPackages                             tiime/monolog-masker - 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. tiime/monolog-masker

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

tiime/monolog-masker
====================

A lightweight, zero-dependency Monolog processor to keep sensitive data and secrets out of your logs.

1.0.0-beta.3(1mo ago)2914↓37%1MITPHPPHP &gt;=8.2CI passing

Since May 29Pushed 1mo agoCompare

[ Source](https://github.com/Tiime-Software/MonologMasker)[ Packagist](https://packagist.org/packages/tiime/monolog-masker)[ RSS](/packages/tiime-monolog-masker/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (3)Dependencies (12)Versions (7)Used By (0)

 [![logo Tiime](https://camo.githubusercontent.com/5b9879db054f83565b9024fb3f692ffa3c9c0e4ad0756aa1806637fb6f6d5f6f/68747470733a2f2f6173736574732e7469696d652e66722f61757468302d756e6976657273616c2d6c6f67696e2f617070732f6c6f676f5f7469696d652e737667)](https://camo.githubusercontent.com/5b9879db054f83565b9024fb3f692ffa3c9c0e4ad0756aa1806637fb6f6d5f6f/68747470733a2f2f6173736574732e7469696d652e66722f61757468302d756e6976657273616c2d6c6f67696e2f617070732f6c6f676f5f7469696d652e737667)
Monolog Masker

[![PHP Version](https://camo.githubusercontent.com/40f996805acf88777b476125c3e627704b6e1e659d1c340aa5819d367c5333c5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d3737374242342e7376673f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/40f996805acf88777b476125c3e627704b6e1e659d1c340aa5819d367c5333c5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d3737374242342e7376673f7374796c653d666c61742d737175617265)[![Monolog Version](https://camo.githubusercontent.com/6aa864c9f3ade22a6a0d64d76241989c7e3315cbaa265966f7f619036c377abb/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4d6f6e6f6c6f672d332e782d626c75652e7376673f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/6aa864c9f3ade22a6a0d64d76241989c7e3315cbaa265966f7f619036c377abb/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4d6f6e6f6c6f672d332e782d626c75652e7376673f7374796c653d666c61742d737175617265)[![License](https://camo.githubusercontent.com/458425f8985b0b0c8a736cffe75e05a098e3d77906acddbcad2bfc54492a4e02/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e7376673f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/458425f8985b0b0c8a736cffe75e05a098e3d77906acddbcad2bfc54492a4e02/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e7376673f7374796c653d666c61742d737175617265)

**A lightweight, zero-dependency Monolog processor to keep sensitive data and secrets out of your logs.**

---

🛑 The Problem
-------------

[](#-the-problem)

When logging requests, exceptions, or context arrays, it's easy to accidentally leak sensitive information like passwords, API keys, or Personally Identifiable Information (PII) into your log files or monitoring systems (Datadog, Sentry, ELK). This can lead to security breaches and GDPR compliance issues.

✅ The Solution
--------------

[](#-the-solution)

`monolog-masker` provides a simple Processor for Monolog that recursively intercepts and masks sensitive keys before they are ever written to your logs.

📦 Installation
--------------

[](#-installation)

You can install the package via composer:

```
composer require tiime/monolog-masker
```

🚀 Quick start
-------------

[](#-quick-start)

Push the processor onto your logger. With the defaults you are protected in one line:

```
use Monolog\Logger;
use Tiime\MonologMasker\MaskerBuilder;

$logger = new Logger('app');
// Push FIRST so Monolog runs it LAST — see "Processor ordering" below.
$logger->pushProcessor(MaskerBuilder::create()->buildProcessor());

$logger->info('payment', [
    'db_password' => 'super-secret',
    'card_number' => '4242 4242 4242 4242',
    'amount'      => 1000,
]);
// context becomes:
// ['db_password' => '████████', 'card_number' => '████████', 'amount' => 1000]
```

The processor walks `message`, `context` and `extra` and masks, **secure by default**:

- **Sensitive keys** — values whose key contains a known sensitive *segment*(`password`, `token`, `api_key`, `authorization`, …). Matching is segment-aware, so compound names like `db_password`, `userToken` or `x-api-key` are caught too (but not `tokenizer`). The whole sub-tree under a sensitive key is collapsed.
- **Sensitive values** — tokens that *look* like a secret or PII (email, IBAN, JWT, `Bearer …`, AWS/Google keys, PEM blocks, and **Luhn-validated** card numbers), wherever they appear — including the log **message**. Only the matched sub-string is masked, so surrounding text is preserved.
- **Objects** in the context are traversed too (`JsonSerializable`, `Stringable`, or public properties), so secrets carried by DTOs don't slip through unmasked.

⚙️ Configuration
----------------

[](#️-configuration)

Everything is wired through the fluent, immutable `MaskerBuilder`:

```
use Tiime\MonologMasker\MaskerBuilder;
use Tiime\MonologMasker\Strategy\PartialMaskStrategy;

$processor = MaskerBuilder::create()
    ->withSensitiveKeys(['x-internal-token'])   // add to the default key list
    ->withValuePatterns(['fr_phone' => '/\b0[1-9](?:\d{2}){4}\b/'])
    ->withStrategy(new PartialMaskStrategy(visible: 4)) // keep last 4 chars: "███1234"
    ->maxDepth(20)
    ->buildProcessor();

$logger->pushProcessor($processor);
```

Other knobs:

- `withKeyMatcher()` / `withValueMatcher()` — replace detection entirely with your own `KeyMatcherInterface` / `ValueMatcherInterface`.
- `withoutValueMatching()` — key-based masking only (skip value detection).
- `withoutValuePatterns(['email', 'iban'])` — drop specific default value patterns by name (keeps the others and card detection).
- `matchKeysExactly()` — whole-string key matching instead of segment-aware (no compound-key detection, fewer false positives).
- `maskMessage(false)` — stop masking the log message.
- `traverseObjects(false)` — leave objects untouched.

### Processor ordering

[](#processor-ordering)

Monolog runs processors in **reverse** of their push order. To also mask the `extra` data added by other processors (e.g. `WebProcessor`), push the masker **first** so it runs **last**.

### Depth limit

[](#depth-limit)

Recursion is bounded by `maxDepth` (default 16); anything deeper — and any object cycle — is replaced with `[TRUNCATED]` rather than traversed.

### JSON inside a string value

[](#json-inside-a-string-value)

Some logs carry a serialized payload as a *string* — typically the raw body of a POST request. Declare those keys with `withJsonKeys()` and the processor decodes the JSON, masks it recursively (same key + value rules), then re-encodes it:

```
$processor = MaskerBuilder::create()
    ->withJsonKeys(['body', 'request_body'])
    ->buildProcessor();

$logger->info('request', ['body' => '{"username":"alice","password":"hunter2"}']);
// context becomes:
// ['body' => '{"username":"alice","password":"████████"}']
```

- **Opt-in**: with no JSON keys declared the behaviour is unchanged — such a string stays an opaque leaf.
- A *decodable* JSON value takes precedence over a sensitive-key match, so a key that is both sensitive and declared JSON is looked *into* rather than collapsed. A non-decodable value (or a JSON scalar) falls back to the normal rules.
- Re-encoding normalises formatting (whitespace, escaping; an empty `{}` comes back as `[]`) — the masked payload is semantically equal, not byte-identical.

### Masking strategies

[](#masking-strategies)

StrategyResultWhen`FullMaskStrategy` (default)`████████`Zero leakage — recommended`PartialMaskStrategy(visible: N)``███1234`Keep a tail for debugging/correlationBoth are configurable (placeholder, mask character, number of visible chars), and you can implement `MaskStrategyInterface` for anything else.

🎼 Symfony integration
---------------------

[](#-symfony-integration)

Register the processor with the MonologBundle via the `monolog.processor` tag.

> **Heads-up:** `MaskerBuilder` is **immutable** (`with*()` returns a new instance), so Symfony's `calls:` cannot configure it. Use the builder as a factory object (defaults) or a small factory class (custom config).

**Defaults — one service:**

```
# config/services.yaml
services:
    monolog_masker.builder:
        class: Tiime\MonologMasker\MaskerBuilder
        factory: ['Tiime\MonologMasker\MaskerBuilder', 'create']

    Tiime\MonologMasker\Processor\MaskingProcessor:
        factory: ['@monolog_masker.builder', 'buildProcessor']
        tags:
            # low priority so it runs LAST and also masks `extra` from other processors
            - { name: monolog.processor, priority: -100 }
```

**Custom config — via a factory class:**

```
// src/Logging/MaskingProcessorFactory.php
namespace App\Logging;

use Tiime\MonologMasker\MaskerBuilder;
use Tiime\MonologMasker\Processor\MaskingProcessor;
use Tiime\MonologMasker\Strategy\PartialMaskStrategy;

final class MaskingProcessorFactory
{
    public static function create(): MaskingProcessor
    {
        return MaskerBuilder::create()
            ->withSensitiveKeys(['x-internal-token'])
            ->withStrategy(new PartialMaskStrategy(visible: 4))
            ->buildProcessor();
    }
}
```

```
# config/services.yaml
services:
    Tiime\MonologMasker\Processor\MaskingProcessor:
        factory: ['App\Logging\MaskingProcessorFactory', 'create']
        tags:
            - { name: monolog.processor, priority: -100 }
```

Scope it to a handler or channel if needed: `- { name: monolog.processor, handler: main }` (or `channel: app`).

🧱 Architecture
--------------

[](#-architecture)

The masking engine is decoupled from Monolog so it can be tested and reused on its own:

- `Masker` — recursive, immutable engine (never mutates its input; traverses arrays and objects; bounded by a max depth that also guards against cycles; optionally decodes/masks/re-encodes JSON held in string values via JSON keys).
- `MaskingProcessor` — thin Monolog adapter (`ProcessorInterface`).
- `Matcher\*` — pluggable detection: keys (`KeyListMatcher`, `SegmentKeyMatcher`) and values (`RegexValueMatcher`, `CreditCardMatcher`, `ChainValueMatcher`).
- `Strategy\*` — pluggable masking (`FullMaskStrategy`, `PartialMaskStrategy`).
- `MaskerBuilder` — fluent factory tying it all together with secure defaults.

✅ Development
-------------

[](#-development)

This package follows the Tiime conventions (Docker + `make`):

```
make install    # install dependencies
make validate   # cs-check + phpstan (max) + coverage + infection + proofs — run before any commit
make test       # unit tests only
make coverage   # unit tests + 100% line/method coverage gate (pcov)
make infection  # mutation testing (MSI 100%)
make proofs     # property-based tests (black-box)
```

The suite is held to **100% line &amp; method coverage** *and* **100% MSI** (mutation score, via [Infection](https://infection.github.io/)). Both are enforced as hard gates in CI, so a weak test that executes code without actually asserting its behaviour fails the build.

On top of the example-based unit tests, the library's **invariants** are checked with **property-based tests** ([innmind/black-box](https://github.com/Innmind/BlackBox)) — idempotence, no-leak, structure preservation, depth bounds, etc. — over hundreds of randomly generated, auto-shrinking inputs. These live in `tests/Property` (suite `property`, run via `make proofs`); coverage and mutation gates stay scoped to the deterministic `unit` suite.

📄 License
---------

[](#-license)

MIT — see [LICENSE](LICENSE).

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance93

Actively maintained with recent releases

Popularity24

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

 Bus Factor1

Top contributor holds 87.5% 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.

###  Release Activity

Cadence

Every ~10 days

Total

3

Last Release

36d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/5444185?v=4)[Flavien Rodrigues](/maintainers/rflavien)[@rflavien](https://github.com/rflavien)

---

Top Contributors

[![rflavien](https://avatars.githubusercontent.com/u/5444185?v=4)](https://github.com/rflavien "rflavien (7 commits)")[![qdequippe](https://avatars.githubusercontent.com/u/3193300?v=4)](https://github.com/qdequippe "qdequippe (1 commits)")

---

Tags

loggingsecuritymonologsecretsgdprpiiMasking

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tiime-monolog-masker/health.svg)

```
[![Health](https://phpackages.com/badges/tiime-monolog-masker/health.svg)](https://phpackages.com/packages/tiime-monolog-masker)
```

###  Alternatives

[naoray/laravel-github-monolog

Log driver to store logs as github issues

10923.3k](/packages/naoray-laravel-github-monolog)[jacklul/monolog-telegram

Monolog handler that sends logs through Telegram bot to any chat in HTML format

2571.4k2](/packages/jacklul-monolog-telegram)[alexandre-daubois/monolog-processor-collection

A collection of Monolog processors

1317.1k](/packages/alexandre-daubois-monolog-processor-collection)

PHPackages © 2026

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