1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19: 20:
21: class Logger extends Object
22: {
23: const DEBUG = 'debug',
24: INFO = 'info',
25: WARNING = 'warning',
26: ERROR = 'error',
27: CRITICAL = 'critical';
28:
29:
30: public static $emailSnooze = 172800;
31:
32:
33: public $mailer = array(__CLASS__, 'defaultMailer');
34:
35:
36: public $directory;
37:
38:
39: public $email;
40:
41:
42:
43: 44: 45: 46: 47: 48:
49: public function log($message, $priority = self::INFO)
50: {
51: if (!is_dir($this->directory)) {
52: throw new DirectoryNotFoundException("Directory '$this->directory' is not found or is not directory.");
53: }
54:
55: if (is_array($message)) {
56: $message = implode(' ', $message);
57: }
58: $res = error_log(trim($message) . PHP_EOL, 3, $this->directory . '/' . strtolower($priority) . '.log');
59:
60: if (($priority === self::ERROR || $priority === self::CRITICAL) && $this->email && $this->mailer
61: && @filemtime($this->directory . '/email-sent') + self::$emailSnooze < time()
62: && @file_put_contents($this->directory . '/email-sent', 'sent')
63: ) {
64: call_user_func($this->mailer, $message, $this->email);
65: }
66: return $res;
67: }
68:
69:
70:
71: 72: 73: 74: 75: 76:
77: private static function defaultMailer($message, $email)
78: {
79: $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] :
80: (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '');
81:
82: $parts = str_replace(
83: array("\r\n", "\n"),
84: array("\n", PHP_EOL),
85: array(
86: 'headers' => "From: noreply@$host\nX-Mailer: Nette Framework\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: