phpsymfonymonolog

Symfony monolog: using multiple formatters


I'm working on a symfony project where we're using already a custom formatter coming from a private library.

monolog:
    handlers:
        main:
            type:  stream
            path:  "%log_file_path%"
            level: "%log_level%"
            formatter: logstash_formatter_private_lib

I want to add a new formatter for filtering out sensitive data. This is why I created a new processor for that:


<?php

namespace App\CoreBundle\Logger;

use Monolog\Processor\ProcessorInterface;

class PIIFilterProcessor implements ProcessorInterface
{
    private $piiFields = ['password', 'email', 'phone', 'address'];

    public function __invoke(array $record)
    {
        // Loop through each PII field and unset it if exists
        foreach ($this->piiFields as $field) {
            if (isset($record['context'][$field])) {
                $record['context'][$field] = '***FILTERED***';
            }
        }

        return $record;
    }
}

How to execute this processor/formatter after or before the one already running?


Solution

  • You need to tag your processor with monolog.processor as described here:

    <?php
    
    namespace App\CoreBundle\Logger;
    
    use Monolog\Processor\ProcessorInterface;
    use Monolog\Attribute\AsMonologProcessor;
    
    #[AsMonologProcessor]
    class PIIFilterProcessor
    {