Better logging
parent
c20cfabb67
commit
1f0ea89f2b
@ -0,0 +1,81 @@
|
|||||||
|
<?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);
|
||||||
|
}
|
||||||
|
|
||||||
|
if(Configuration::get('log.verbosity') > Logger::QUIET) {
|
||||||
|
$time = (microtime(true) - self::$start) * 1000;
|
||||||
|
self::$data['time'] = round($time, 2).'ms';
|
||||||
|
|
||||||
|
$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_put_contents(Configuration::get('log.file'), $msg, FILE_APPEND | LOCK_EX);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue