I am trying to figure out how I can send errors to my email in Laravel 5. I haven\'t had much luck finding any good resources.
There used to be good packages like: http
/config/logging.php
// ...
'monitoring-mail' => [
'driver' => 'custom',
'via' => App\Logging\Mail::class,
'level' => env('LOG_MONITORING_MAIL_LEVEL', 'error'),
'to' => env('LOG_MONITORING_TO'),
'from' => env('LOG_MONITORING_FROM'),
],
// ...
/app/Logging/Mail.php
<?php
namespace App\Logging;
use App\Helpers\Log\MailHandler;
use Monolog\Logger;
class Mail
{
public function __invoke(array $config)
{
$handler = new MailHandler($config['to'], $config['level'], $config['bubble'] ?? true, $config);
return new Logger('mail', [$handler]);
}
}
/app/Helpers/Log/MailHandler.php
<?php
namespace App\Helpers\Log;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
class MailHandler extends AbstractProcessingHandler
{
/** @var string */
protected $to;
/** @var array */
protected $config;
public function __construct(string $to, $level = Logger::DEBUG, bool $bubble = true, ?array $config = null)
{
parent::__construct($level, $bubble);
if (empty($to)) {
throw new \InvalidArgumentException('"To" cannot be empty');
}
$this->to = $to;
$this->config = (array) $config;
}
protected function write(array $record): void
{
$body = $record['formatted'] ?? $record['message'] ?? '<empty>';
Mail::raw($body, function (Message $message) use ($record) {
$subject = ($record['level_name'] ?? 'ERROR') . ': ' . ($record['message'] ?? '<empty>');
$message->to($this->to);
$message->subject($subject);
if (!empty($this->config['from'])) {
$message->from($this->config['from']);
}
});
}
}
Here is the solution for Laravel 5.3
#file: /app/Exceptions/Handler.php
public function report(Exception $e)
{
if($this->shouldReport($e)){
\Mail::send(
['html' => 'error.emails.exception'],
['content' => $data['content']],
function ($m) {
$m->from(['myemail@from.com']);
$m->to(['myemail@to.com']);
$m->subject('Crash Report');
}
);
}
parent::report($e);
}
Theres a package here https://github.com/designmynight/laravel-log-mailer that adds a mail driver to Laravel 5.6's LogManager which should do exactly what you are after.
There are configuration settings in the config/logging.php file and you can create different mail channels for logging information to different recipients. The email template is also customisable.