4
* This file is part of the Nette Framework (http://nette.org)
6
* Copyright (c) 2004 David Grudl (http://davidgrudl.com)
8
* For the full copyright and license information, please view
9
* the file license.txt that was distributed with this source code.
12
namespace Nette\Diagnostics;
22
class Logger extends Nette\Object
24
const DEBUG = 'debug',
28
CRITICAL = 'critical';
30
/** @var int interval for sending email is 2 days */
31
public static $emailSnooze = 172800;
33
/** @var callable handler for sending emails */
34
public $mailer = array(__CLASS__, 'defaultMailer');
36
/** @var string name of the directory where errors should be logged; FALSE means that logging is disabled */
39
/** @var string email to sent error notifications */
44
* Logs message or exception to file and sends email notification.
46
* @param int one of constant INFO, WARNING, ERROR (sends email), CRITICAL (sends email)
47
* @return bool was successful?
49
public function log($message, $priority = self::INFO)
51
if (!is_dir($this->directory)) {
52
throw new Nette\DirectoryNotFoundException("Directory '$this->directory' is not found or is not directory.");
55
if (is_array($message)) {
56
$message = implode(' ', $message);
58
$res = error_log(trim($message) . PHP_EOL, 3, $this->directory . '/' . strtolower($priority) . '.log');
60
if (($priority === self::ERROR || $priority === self::CRITICAL) && $this->email && $this->mailer
61
&& @filemtime($this->directory . '/email-sent') + self::$emailSnooze < time() // @ - file may not exist
62
&& @file_put_contents($this->directory . '/email-sent', 'sent') // @ - file may not be writable
64
Nette\Callback::create($this->mailer)->invoke($message, $this->email);
76
public static function defaultMailer($message, $email)
78
$host = php_uname('n');
79
foreach (array('HTTP_HOST','SERVER_NAME', 'HOSTNAME') as $item) {
80
if (isset($_SERVER[$item])) {
81
$host = $_SERVER[$item]; break;
89
'headers' => implode("\n", array(
90
"From: noreply@$host",
91
'X-Mailer: Nette Framework',
92
'Content-Type: text/plain; charset=UTF-8',
93
'Content-Transfer-Encoding: 8bit',
95
'subject' => "PHP: An error occurred on the server $host",
96
'body' => "[" . @date('Y-m-d H:i:s') . "] $message", // @ - timezone may not be set
100
mail($email, $parts['subject'], $parts['body'], $parts['headers']);