You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
111 lines
2.7 KiB
111 lines
2.7 KiB
<?php
|
|
|
|
define('PROJECT_LOGS_DIR', $cwd. '/log');
|
|
|
|
class logger {
|
|
|
|
private $handle;
|
|
|
|
/**
|
|
* Get Filename for writing to Log file
|
|
* @param string $filename for log
|
|
* @param int $max_count of lines before file wipe, to keep small logs.
|
|
*/
|
|
public function __construct(string $filename = 'neato_Installer', int $max_count = 1000) {
|
|
if (strpos($filename, "..") !== false) {
|
|
$this->handle = false; // Too dangerious, so return false
|
|
} else {
|
|
$filename = str_replace("php", "", $filename);
|
|
if (! is_dir(PROJECT_LOGS_DIR)){
|
|
//Directory does not exist, so lets create it.
|
|
mkdir(PROJECT_LOGS_DIR, 0775);
|
|
}
|
|
|
|
$filename = preg_replace("|[^A-Za-z0-9_]|", "", $filename);
|
|
$filename = escapeshellcmd($filename);
|
|
$file = PROJECT_LOGS_DIR . '/' . $filename . ".log.txt";
|
|
|
|
if ($max_count > 1) {
|
|
if ($this->get_lines($file) > $max_count) {
|
|
unlink($file);
|
|
}
|
|
}
|
|
|
|
$success = touch($file);
|
|
if ($success === false) {
|
|
$this->handle = false;
|
|
return false;
|
|
}
|
|
chmod($file, 0660);
|
|
if (! is_writable($file)) {
|
|
$this->handle = false;
|
|
return false;
|
|
}
|
|
$this->handle = fopen($file, 'a');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Count number of lines in Log File
|
|
* @param string $file
|
|
* @return int line count
|
|
*/
|
|
public function get_lines(string $file): int {
|
|
// No such file, so return zero for length.
|
|
if (! file_exists($file)) {
|
|
return 0;
|
|
}
|
|
|
|
$f = fopen($file, 'rb');
|
|
$lines = 0;
|
|
|
|
if ($f === false || !is_resource($f)) {
|
|
return 0;
|
|
}
|
|
|
|
while (!feof($f)) {
|
|
$line = fread($f, 8192);
|
|
if ($line === false) {
|
|
return 0;
|
|
}
|
|
$lines += substr_count($line, "\n");
|
|
}
|
|
|
|
fclose($f);
|
|
|
|
return $lines;
|
|
}
|
|
|
|
/**
|
|
* Write to Log File
|
|
* @param string $message to save
|
|
* @return bool able to write to log file
|
|
*/
|
|
public function write(string $message): bool {
|
|
if ( $this->handle === false || ! is_resource($this->handle) ) {
|
|
return false;
|
|
}
|
|
$tz = configure::get('logger_time_zone');
|
|
if ($tz !== false && !empty($tz)) {
|
|
$tz_obj = new \DateTimeZone($tz);
|
|
$dt = new \DateTime();
|
|
$dt->setTimezone($tz_obj);
|
|
$now = $dt->format('g:i A \o\n l jS F Y');
|
|
} else {
|
|
$dt = new \DateTime();
|
|
$now = $dt->format('g:i A \o\n l jS F Y');
|
|
}
|
|
fwrite($this->handle, $now . ' - ' . print_r($message, true) . "\n");
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Close Log File Handle
|
|
*/
|
|
public function __destruct() {
|
|
if ($this->handle !== false && is_resource($this->handle)) {
|
|
fclose($this->handle);
|
|
}
|
|
}
|
|
|
|
} // end of Logger
|
|
|