Skip to content

Instantly share code, notes, and snippets.

@cuonghuynh
Created October 22, 2018 07:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuonghuynh/f9f7f651e3f12933dd96b45cedaa44c7 to your computer and use it in GitHub Desktop.
Save cuonghuynh/f9f7f651e3f12933dd96b45cedaa44c7 to your computer and use it in GitHub Desktop.
Symfony: Mask sensitive data in the log file

Add processor to monolog handler

<service id="shopmacher.payment.logger.handler" class="Monolog\Handler\StreamHandler">
    //...
    <call method="pushProcessor">
        <argument type="service" id="service_processor.payment_logger_filtering" />
    </call>
</service>

Processor service

class PaymentLoggerFiltering
{
    /**
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    /**
     * PaymentLoggerFiltering constructor.
     * @param EventDispatcherInterface $eventDispatcher
     */
    public function __construct(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * @param array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        $event = new PaymentLoggerFilteringEvent($record);
        $this->eventDispatcher->dispatch(PaymentLoggerFilteringEvent::NAME, $event);

        return $event->getRecord();
    }
}

Listener

public static function getSubscribedEvents()
{
    return [
        PaymentLoggerFilteringEvent::NAME => ['maskData', 128]
    ];
}

/**
 * @param PaymentLoggerFilteringEvent $event
 */
public function maskData(PaymentLoggerFilteringEvent $event)
{
    $record = $event->getRecord();
    $record['context'] = $this->maskCreditCardInfo($record['context']);
    $record['context'] = $this->maskIBAN($record['context']);

    $event->setRecord($record);
}

Data masker helper

/**
 * Class DataMasker
 */
class DataMasker
{
  //...
  protected function maskText(string $text)
  {
      $len = \strlen($text);
      $unmaskedLen = self::UNMASKED_LEN * 2;
      if ($len > self::MAX_LEN) {
          $firstChars = substr($text, 0, self::UNMASKED_LEN);
          $lastChars = substr($text, $len -self::UNMASKED_LEN, self::UNMASKED_LEN);
          $hiddenChars = str_repeat(self::MASKING_CHAR, $len - $unmaskedLen);

          return $firstChars.$hiddenChars.$lastChars;
      }

      return str_repeat(self::MASKING_CHAR, $len);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment