1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19: 20:
21: class NLogger extends NObject
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: public function log($message, $priority = self::INFO)
49: {
50: if (!is_dir($this->directory)) {
51: throw new DirectoryNotFoundException("Directory '$this->directory' is not found or is not directory.");
52: }
53:
54: if (is_array($message)) {
55: $message = implode(' ', $message);
56: }
57: $res = error_log(trim($message) . PHP_EOL, 3, $this->directory . '/' . strtolower($priority) . '.log');
58:
59: if (($priority === self::ERROR || $priority === self::CRITICAL) && $this->email && $this->mailer
60: && @filemtime($this->directory . '/email-sent') + self::$emailSnooze < time()
61: && @file_put_contents($this->directory . '/email-sent', 'sent')
62: ) {
63: NCallback::create($this->mailer)->invoke($message, $this->email);
64: }
65: return $res;
66: }
67:
68:
69: 70: 71: 72: 73: 74:
75: public static function defaultMailer($message, $email)
76: {
77: $host = php_uname('n');
78: foreach (array('HTTP_HOST','SERVER_NAME', 'HOSTNAME') as $item) {
79: if (isset($_SERVER[$item])) {
80: $host = $_SERVER[$item]; break;
81: }
82: }
83:
84: $parts = str_replace(
85: array("\r\n", "\n"),
86: array("\n", PHP_EOL),
87: array(
88: 'headers' => implode("\n", array(
89: "From: noreply@$host",
90: 'X-Mailer: Nette Framework',
91: 'Content-Type: text/plain; charset=UTF-8',
92: 'Content-Transfer-Encoding: 8bit',
93: )) . "\n",
94: 'subject' => "PHP: An error occurred on the server $host",
95: 'body' => "[" . @date('Y-m-d H:i:s') . "] $message",
96: )
97: );
98:
99: mail($email, $parts['subject'], $parts['body'], $parts['headers']);
100: }
101:
102: }
103: