PHPackages                             sirix/monolog-redaction - 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. sirix/monolog-redaction

Abandoned → [sirix/redaction](/?search=sirix%2Fredaction)ArchivedLibrary[Logging &amp; Monitoring](/categories/logging)

sirix/monolog-redaction
=======================

Deprecated: functionality moved to sirix/redaction

2.0.1(6mo ago)066MITPHPPHP ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0CI passing

Since Oct 10Pushed 6mo agoCompare

[ Source](https://github.com/sirix777/monolog-redaction)[ Packagist](https://packagist.org/packages/sirix/monolog-redaction)[ RSS](/packages/sirix-monolog-redaction/feed)WikiDiscussions main Synced 1mo ago

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

Monolog Redaction Processor
===========================

[](#monolog-redaction-processor)

⚠️ Deprecated: sirix/monolog-redaction
======================================

[](#️-deprecated-sirixmonolog-redaction)

This package is **no longer maintained**.

All functionality has been moved to **[`sirix/redaction`](https://github.com/sirix777/redaction)**.

Monolog processor for redacting sensitive information in logs.

This library provides a Processor for Monolog 3 that traverses your log context (arrays, objects, iterables) and masks sensitive values using pluggable rules. It ships with a sensible set of default rules (card data, emails, names, IPs, etc.) and lets you add your own or override per key.

- PHP 8.1–8.4
- Monolog ^3.0
- License: MIT

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

[](#installation)

Install via Composer:

```
composer require sirix/monolog-redaction

```

Quick start
-----------

[](#quick-start)

```
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Sirix\Monolog\Redaction\RedactorProcessor;
use Sirix\Monolog\Redaction\Rule\StartEndRule;
use Sirix\Monolog\Redaction\Rule\EmailRule;
use Sirix\Monolog\Redaction\Rule\NameRule;

$logger = new Logger('app');
$logger->pushHandler(new StreamHandler('php://stdout'));

// By default, the processor loads built‑in rules. You can pass custom rules below.
$processor = new RedactorProcessor([
    // Overwrite or add rules per key
    'card_number' => new StartEndRule(6, 4),
    'user' => [ // nested structure rules
        'email' => new EmailRule(),
        'name'  => new NameRule(),
    ],
]);

// Optional tuning
$processor->setReplacement('*');       // character used to mask
$processor->setTemplate('%s');          // how the mask is rendered; e.g. '[%s]' to wrap
$processor->setLengthLimit(null);       // limit the resulting masked string length (or null for no limit)

$logger->pushProcessor($processor);

$logger->info('User checkout', [
    'card_number' => '1234567890123456',
    'user' => [
        'email' => 'john.doe@example.com',
        'name'  => 'John Doe',
        'phone' => '+44123456789012',
    ],
]);
```

Example output (stdout):

```
[info] app: User checkout {"card_number":"123456******3456","user":{"email":"joh****@example.com","name":"J*** D**","phone":"+4412****12"}}

```

Note: Exact output format depends on your handler/formatter. The masking shown reflects the default rules plus the ones configured above.

How it works
------------

[](#how-it-works)

- The processor recursively walks through scalars in your context and applies a rule when a key matches.
- Scalars at the top level (no key) are processed by all rules that operate on plain strings.
- For arrays/objects, you can specify nested rule maps that apply to the child structure.

Default rules
-------------

[](#default-rules)

By default, `RedactorProcessor` loads a curated set of rules for common sensitive fields (card numbers/PAN, CVV, expiry, names, emails, phone, IPs, addresses, tokens, 3‑D Secure fields, etc.). See `src/Rule/Default/default_rules.php` for the complete list.

To disable default rules and use only your own:

```
$processor = new RedactorProcessor(customRules: [], useDefaultRules: false);
```

Built‑in rule types
-------------------

[](#builtin-rule-types)

These rules live under `Sirix\Monolog\Redaction\Rule` and can be combined as needed:

- StartEndRule($visibleStart, $visibleEnd): masks the middle part of a string, keeping given number of characters at the start/end.
- EmailRule: masks the local part of an email, keeping the first 3 characters and the full domain.
- PhoneRule: masks digits in the middle of a phone number, keeping the first 4 and last 2 digits when possible.
- FullMaskRule: replaces the entire value with the replacement character(s).
- FixedValueRule($replacement): always outputs the provided constant string (e.g., `*` or `**/****`).
- NameRule: masks personal names leaving just initials and/or a few characters as defined by the rule.
- NullRule: sets the value to null.

If you need a custom masking strategy, implement `RedactionRuleInterface`:

```
use Sirix\Monolog\Redaction\Rule\RedactionRuleInterface;
use Sirix\Monolog\Redaction\RedactorProcessor;

final class MyRule implements RedactionRuleInterface
{
    public function apply(string $value, RedactorProcessor $processor): ?string
    {
        // Return the masked string, or null to indicate no change
        return '***';
    }
}
```

Processor options
-----------------

[](#processor-options)

- setReplacement(string $char): character used to construct masks (default `*`).
- setTemplate(string $template): a `sprintf` template applied to the mask string (default `'%s'`). For example, `'[%s]'` wraps mask in brackets.
- setLengthLimit(?int $limit): if set, truncates the resulting masked value to at most this length.
- setObjectViewMode(ObjectViewModeEnum $mode): controls how objects are traversed/represented (default `Copy`).
    - Copy: convert objects to stdClass and include non‑public properties when needed (backward compatible default).
    - PublicArray: build an array from public properties only using `get_object_vars`, then process that array (fast path; no reflection).
    - Skip: do not traverse objects; replace them with a short placeholder string like \[object ClassName\].
- setMaxDepth(?int $depth): limit recursion depth while traversing arrays/objects (default `null` = no limit).
- setMaxItemsPerContainer(?int $count): process at most this many elements per array container (default `null` = no limit). Remaining items stay untouched.
- setMaxTotalNodes(?int $count): global cap on visited/processed nodes across the whole structure (default `null` = no limit).
- setOnLimitExceededCallback(?callable $cb): telemetry callback invoked on any limit or cycle event. Signature: `function (array $info): void`.
- setOverflowPlaceholder(mixed $value): placeholder value used when a limit is hit (default `null` = keep original value to preserve backward compatibility).

These options are used by rules that build masks based on hidden length (e.g., StartEndRule, PhoneRule). The traversal limits are fully opt‑in; with defaults (all `null`), the processor behaves exactly as before.

Example: enabling traversal limits and telemetry

```
$processor = new RedactorProcessor();

$processor->setMaxDepth(5);
$processor->setMaxItemsPerContainer(100);
$processor->setMaxTotalNodes(10_000);
$processor->setOverflowPlaceholder('…'); // replace skipped parts with an ellipsis
$processor->setOnLimitExceededCallback(function (array $info): void {
    // Example fields: type (maxDepth|maxItemsPerContainer|maxTotalNodes|cycle),
    // depth, nodesVisited, key/kind/class (when applicable)
    // You can forward this to metrics/logs.
});
```

Notes:

- Arrays: when `maxItemsPerContainer` is reached, iteration stops for that container; remaining items are left as‑is (or replaced with `overflowPlaceholder` only for the current item when applicable).
- Objects: cycles are detected via `SplObjectStorage`; on repeat, the callback is fired and the value is left as‑is or replaced by `overflowPlaceholder` if configured.
- Node counting: `nodesVisited` increments per array element and per object property processed; `maxTotalNodes` stops further processing and optionally applies the placeholder to the current node.

Error Handling
--------------

[](#error-handling)

Since v1.1.0, the processor provides improved error handling through a dedicated exception class:

- `RedactorReflectionException`: Thrown when reflection errors occur during object processing, providing more context about what caused the issue.

This helps with debugging issues related to processing complex object structures.

Testing &amp; QA
----------------

[](#testing--qa)

This repository includes a PHPUnit test suite and tooling configs.

- Run tests: `composer test`
- Static analysis: `composer phpstan`
- Code style check: `composer cs-check`
- Auto‑fix style: `composer cs-fix`

Breaking changes in 2.0.0
-------------------------

[](#breaking-changes-in-200)

- Removed setProcessObjects(bool $processObjects). Use setObjectViewMode(ObjectViewModeEnum::Skip) to avoid processing objects entirely, or ObjectViewModeEnum::PublicArray to process only public properties without reflection.
- If you previously disabled object processing for performance, switching to PublicArray often provides a good balance between safety and speed.

Versioning
----------

[](#versioning)

- PHP: ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0
- Monolog: ^3.0

License
-------

[](#license)

MIT © Sirix

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance66

Regular maintenance activity

Popularity8

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

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 ~1 days

Total

11

Last Release

199d ago

Major Versions

1.3.1 → 2.0.02025-10-22

### Community

Maintainers

![](https://www.gravatar.com/avatar/6ecccf9003c061847e877eeea3bdf1b382f6f9dbb11d33112d6b2740bf0533f9?d=identicon)[sirix777](/maintainers/sirix777)

---

Tags

loggingmonologprocessorredactiongdprprivacypiiredactMasking

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/sirix-monolog-redaction/health.svg)

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

###  Alternatives

[inpsyde/wonolog

Monolog-based logging package for WordPress.

183617.9k6](/packages/inpsyde-wonolog)[logtail/monolog-logtail

Logtail handler for Monolog

233.2M3](/packages/logtail-monolog-logtail)[egeniq/monolog-gdpr

Some Monolog processors that will help in relation to the security requirements under GDPR.

538.7k](/packages/egeniq-monolog-gdpr)[kdyby/monolog

Integration of Monolog into Nette Framework

33684.0k10](/packages/kdyby-monolog)[inpsyde/logzio-monolog

Logz.io integration for Monolog

191.2M1](/packages/inpsyde-logzio-monolog)[mead-steve/mono-snag

Bugsnag integration for monolog. An abstract handler that sends messages to Bugsnag

20533.2k1](/packages/mead-steve-mono-snag)

PHPackages © 2026

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