You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.3 KiB
PHP

<?php
namespace BSR\Lib;
class Logger {
const QUIET = 0;
const NORMAL = 1;
const VERBOSE = 2;
private static $start;
private static $data = array();
private static $log = '';
private static function ip() {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return array_shift(
array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']))
);
} else if (isset($_SERVER['REMOTE_ADDR'])) {
return $_SERVER['REMOTE_ADDR'];
}
return '(n-a)';
}
public static function start() {
self::$start = microtime(true);
self::$data = array(
'ip' => self::ip(),
'date' => date('d.m.Y H:m:s'),
'func' => '(none)',
'error' => ''
);
}
public static function info($info, $key = null) {
if(is_null($key)) {
self::$data = array_merge(self::$data, $info);
} else {
self::$data[$key] = $info;
}
}
/**
* Log a message that will be displayed in the logs if the configuration
* says so.
*
* @param string $message
* @param int $verbosity
*/
public static function log($message, $verbosity = Logger::VERBOSE) {
if(Configuration::get('log.verbosity') < $verbosity) {
return;
}
self::$log .= $message."\n";
}
public static function stop($data = null) {
if(! is_null($data)) {
self::info($data);
}
$time = (microtime(true) - self::$start) * 1000;
self::$data['time'] = round($time, 2).'ms';
if(Configuration::get('log.verbosity') > Logger::QUIET) {
$format = Configuration::get('log.format');
$patterns = array_map(function($p) { return "%$p%"; }, array_keys(self::$data));
$msg = str_replace($patterns, array_values(self::$data), $format)."\n";
if(strlen(self::$log) > 0) {
$msg .= self::$log;
}
$file = Configuration::get('log.file');
if(! file_exists($file)) {
mkdir(dirname($file), 0777, true);
touch($file);
}
file_put_contents($file, $msg, FILE_APPEND | LOCK_EX);
}
}
public static function data() {
return self::$data;
}
}