PHP code example of sirix / monolog-redaction

1. Go to this page and download the library: Download sirix/monolog-redaction library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sirix / monolog-redaction example snippets


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' => '[email protected]',
        'name'  => 'John Doe',
        'phone' => '+44123456789012',
    ],
]);

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

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 = 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.
});