1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Tracy;
9:
10: use Tracy;
11:
12:
13: 14: 15: 16: 17:
18: class Logger
19: {
20: const DEBUG = 'debug',
21: INFO = 'info',
22: WARNING = 'warning',
23: ERROR = 'error',
24: EXCEPTION = 'exception',
25: CRITICAL = 'critical';
26:
27:
28: public $emailSnooze = 172800;
29:
30:
31: public $mailer = array(__CLASS__, 'defaultMailer');
32:
33:
34: public $directory;
35:
36:
37: public $email;
38:
39:
40: 41: 42: 43: 44: 45:
46: public function log($message, $priority = NULL)
47: {
48: if (!is_dir($this->directory)) {
49: throw new \RuntimeException("Directory '$this->directory' is not found or is not directory.");
50: }
51:
52: if (is_array($message)) {
53: $message = implode(' ', $message);
54: }
55: $message = preg_replace('#\s*\r?\n\s*#', ' ', trim($message));
56: $file = $this->directory . '/' . strtolower($priority ?: self::INFO) . '.log';
57: if (!@file_put_contents($file, $message . PHP_EOL, FILE_APPEND | LOCK_EX)) {
58: throw new \RuntimeException("Unable to write to log file '$file'. Is directory writable?");
59: }
60:
61: if (in_array($priority, array(self::ERROR, self::EXCEPTION, self::CRITICAL), TRUE) && $this->email && $this->mailer
62: && @filemtime($this->directory . '/email-sent') + $this->emailSnooze < time()
63: && @file_put_contents($this->directory . '/email-sent', 'sent')
64: ) {
65: call_user_func($this->mailer, $message, implode(', ', (array) $this->email));
66: }
67: }
68:
69:
70: 71: 72: 73: 74: 75:
76: public static function defaultMailer($message, $email)
77: {
78: $host = preg_replace('#[^\w.-]+#', '', isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n'));
79: $parts = str_replace(
80: array("\r\n", "\n"),
81: array("\n", PHP_EOL),
82: array(
83: 'headers' => implode("\n", array(
84: "From: noreply@$host",
85: 'X-Mailer: Tracy',
86: 'Content-Type: text/plain; charset=UTF-8',
87: 'Content-Transfer-Encoding: 8bit',
88: )) . "\n",
89: 'subject' => "PHP: An error occurred on the server $host",
90: 'body' => "[" . @date('Y-m-d H:i:s') . "] $message",
91: )
92: );
93:
94: mail($email, $parts['subject'], $parts['body'], $parts['headers']);
95: }
96:
97: }
98: