How can I get email notifications for exceptions?

This didn't seem as readily accessible as I thought it should be from some searching I did, so I'm posting up a question question/answer for future reference.

Thrown Exceptions

You can enable email notifications for exceptions that are thrown using errors/local.xml. You can copy your errors/local.xml.template to `errors/local.xml' and drop in the email address and subject line that you want to use.

<config>
    <skin>default</skin>
    <report>
        <action>email</action>
        <subject>domain.com exception</subject>
        <email_address>[email protected]</email_address>
        <trash>leave</trash>
    </report>
</config>

Then, if any exceptions are thrown and caught by Magento's error handling system, where an error report screen is displayed to the end user, you'll get an email notification.

Logged Exceptions

If you would also like to get email notifications for exceptions that aren't thrown but rather are logged, you'll need to get a little bit further under the hood.

First, override the core log writer class.

Once you've done that, just drop in the code to shoot yourself an email after the exception is logged. Remember that you need to save the log filename from within the __construct() in order to have access to it from the _write() method.

class Module_Core_Model_Zend_Log_Writer_Stream extends Zend_Log_Writer_Stream
{
    protected $_streamOrUrl;

    public function __construct($streamOrUrl, $mode = NULL)
    {
        parent::__construct($streamOrUrl, $mode);

        $this->_streamOrUrl = $streamOrUrl;
    }

    protected function _write($event)
    {
        parent::_write($event);

        if (strpos($this->_streamOrUrl, 'exception.log') === false) {
            return;
        }

        // Send email here    
    }
}

Emailing every exception will probably result in a LOT of mail.

It might be a better option to just log the exceptions to the exception log and mail that once a day to yourself using a cronjob in linux

0 23 * * * /usr/lib/sendmail [email protected] < /home/shop.com/www/var/log/exception.log

And optionally cleaning it up after you've mailed it

0 23 * * * /usr/lib/sendmail [email protected] < /home/shop.com/www/var/log/exception.log;rm /home/shop.com/www/var/log/exception.log

Or you could execute it every hour if you need a higher frequency.

This way there is no need to overwrite any files and keeping the load on the server that constantly sending mails to yourself down.


You can use the Magento Hackthon Logger for this job: https://github.com/firegento/firegento-logger/

It is not the question, but there are extensions for the extension: https://github.com/magento-hackathon/LoggerSentry/

What I want to say: It is easy to implement your own "Writer" :-)