Posts Tagged ‘logging’

Following my previous posts about logging, let’s create an email logger with Swift.

Swift is the Symfony 1.1 prefered solution for sending emails. For more information about how to use the Swift libraries, referer to the cookbook page.

Declaring sfMailLogger

Once Swift is correctly set up on your project, let’s create our mail logger in /lib/sfMailLogger.class.php :

class sfMailLogger extends sfLogger
{
  protected
    $mailer,
    $recipients;

  public function initialize(sfEventDispatcher $dispatcher, $options = array())
  {
    if (!isset($options['sender']))
    {
      $message = 'You must provide a sender parameter for this logger';
      throw new sfConfigurationException($message);
    }
    if (!isset($options['smtp']))
    {
      $message = 'You must provide a "smtp" parameter for this logger';
      throw new sfConfigurationException($message);
    }
    if (!isset($options['recipients']))
    {
      $message = 'You must provide a "recipients" parameter for this logger';
      throw new sfConfigurationException($message);
    }
    
    $connection       = new Swift_Connection_SMTP($options['smtp']);
    $this->mailer     = new Swift($connection);
    $this->recipients = new Swift_RecipientList();
    $this->sender     = $options['sender'];
    $this->recipients->addTo($options['recipients']);

    return parent::initialize($dispatcher, $options);
  }

  protected function doLog($message, $priority)
  {
    $this->message    = new Swift_Message(log‘, $message);
  }

  public function shutdown()
  {
    $this->mailer->send($this->message, $this->recipients, $this->sender);
  }
} 

Creating a new log event

As we don’t want to send all log messages by email, let’s create a special log event that we are going to trigger separatly.

The best place to put events declarations is in the application configuration class :

$mail_logger = new sfMailLogger(new sfEventDispatcher, array(
  ’recipients‘ => ’nicolas@domain.com‘,
  ’sender‘     => ’noreply@domain.com‘,
  ’smtp‘       => ’mail.domain.com
));

$this->dispatcher->connect(mail.log‘, array($mail_logger, ‘listenToLogEvent‘));

Notifying the mail.log event

Now, you can email-log infos anywhere in your application by notifying the mail.log event :

$dispatcher = sfContext::getInstance()->getEventDispatcher();
$dispatcher->notify(new sfEvent($this, ‘mail.log‘, array(‘hello‘)));
Advertisements