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