0

Helo people,

In my project, sometimes I need to send emails and log messages. The thing is that I'm not using swift mailer, I'm using an API that takes care of sending emails for me.

The solution I've tried is that I created a custom processor where I injected my client mailer. I've followed http://symfony.com/doc/current/cookbook/logging/monolog.html#adding-a-session-request-token.

So I have something like the following:

namespace Tools\LoggerBundle;

use Symfony\Component\HttpFoundation\Session\Session;

class CustomProcessor
{
    private $session;
    private $token;
    // Client Mailer
    private $mailer;

    public function __construct(Session $session, $mailer)
    {
        $this->session = $session;
        $this->mailer = $mailer;
    }

    public function processRecord(array $record)
    {
        if (null === $this->token) {
            try {
                $this->token = substr($this->session->getId(), 0, 8);
            } catch (\RuntimeException $e) {
                $this->token = '????????';
            }
            $this->token .= '-' . substr(uniqid(), -8);
        }
        $record['extra']['token'] = $this->token;

        // Sends an email    
        $this->mailer->send('Alert', print_r($record, true));

        return $record;
    }
}

This works pretty well, except I need to send emails only when level is greater than warning. At the same time, normal logging shouldn't stop.

What do you suggest?

smarber
  • 4,829
  • 7
  • 37
  • 78
  • perhaps it's duplicated http://stackoverflow.com/questions/10261272/symfony2-monolog-settings-for-email-and-file-logging – Abdallah Arffak Dec 31 '14 at 15:25
  • The only difference is that I'm not using swift_mailer like in the post you gave. I should consider using a custom handler though... – smarber Dec 31 '14 at 15:32

1 Answers1

0

You should use class Handler for email sending instead of doing it on processoser

<?php

use Monolog\Handler\AbstractProcessingHandler;

class EmailHandler extends AbstractProcessingHandler
{
    private $mailer;

    public function __construct($mailer, $level = Logger::WARNING, $bubble = true)
    {
        parent::__construct($level, $bubble);
        $this->mailer = $mailer;
    }

    protected function write(array $record)
    {
        $this->mailer->send($record['level_name'], print_r($record, true));
    }
}