/
MailLogWriter.php
67 lines (57 loc) · 1.75 KB
/
MailLogWriter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
/*
* Mendo Framework
*
* (c) Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mendo\Logger\Writer;
use Psr\Log\AbstractLogger;
use \Swift_Mailer;
use \Swift_Message;
/**
* Writes log information out as mail messages.
*
* @author Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
*/
class MailLogWriter extends AbstractLogger
{
use GetStackTraceTrait;
private $mailer;
private $from;
private $to;
/**
* @param Swift_Mailer $mailer
* @param string|array $from
* @param string|array $to
*/
public function __construct(Swift_Mailer $mailer, $from, $to)
{
$this->mailer = $mailer;
$this->from = $from;
$this->to = $to;
}
/**
* @param string $level
* @param string $message
* @param array $context
*/
public function log($level, $message, array $context = [])
{
$message = '['.strtoupper($level).'] '.$message;
$messageInstance = Swift_Message::newInstance()
->setSubject(substr($message, 0, 255))
->setFrom($this->from)
->setTo($this->to);
if (isset($context['exception']) && $context['exception'] instanceof \Exception) {
$messageInstance->setBody($message.$this->getExceptionStackTrace($context['exception']), 'text/html')
->addPart($message.$this->getExceptionStackTrace($context['exception'], false), 'text/plain');
} else {
$messageInstance->setBody($message, 'text/html')
->addPart($message, 'text/plain');
}
$this->mailer->send($messageInstance);
}
}