FRED™  3.0
FRED™: Framework for Rapid and Easy Development
Mem.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Rsi\Fred\Log\Handler;
4 
5 class Mem extends \Rsi\Fred\Log\Handler{
6 
7  public $messages = [];
8  public $maxSize = 1024; //!< Maximum number of messages to store (empty = unlimited).
9  public $save = null; //!< Number of logs to save.
10  public $filename = null; //!< Filename to store logs.
11  public $mode = 0666;
12 
13  public function add($prio,$message,$context){
14  if($this->maxSize && (count($this->messages) >= $this->maxSize))
15  $this->messages = array_slice($this->messages,$this->maxSize >> 1);
16  $this->messages[] = ['time' => microtime(true)] + compact('prio','message','context');
17  }
18 
19  protected function init(){
20  parent::init();
21  if($this->save) $this->_log->component('event')->listen(\Rsi\Fred::EVENT_HALT,[$this,'save']);
22  }
23 
24  public function save(){
25  $log = [
26  'start' => $this->_log->fred->startTime,
27  'end' => microtime(true),
28  'file' => $_SERVER['REQUEST_URI'] ?? $_SERVER['PHP_SELF'] ?? null,
29  'mem' => memory_get_peak_usage(true),
30  'get' => $_GET,
31  'post' => $_POST,
32  'code' => http_response_code(),
33  'session' => $_SESSION,
34  'server' => $_SERVER,
35  'messages' => $this->messages
36  ];
37  if($this->_log->fred->has('db')){
38  $db = $this->_log->fred->db;
39  $log['db'] = ['count' => $db->queryCount,'time' => $db->queryTime];
40  }
41  if(!$this->filename) $this->filename = \Rsi\File::tempDir() . 'log.dat';
42  try{
43  $logs = array_slice(\Rsi\File::unserialize($this->filename,[]) ?: [],1 - $this->save,null,true);
44  $logs[\Rsi\Str::random()] = $log;
45  \Rsi\File::serialize($this->filename,$logs,$this->mode);
46  }
47  catch(\Exception $e){
48  \Rsi\File::unlink($this->filename);
49  $this->_log->component('log')->error($e);
50  }
51  }
52 
53 }
add($prio, $message, $context)
Definition: Mem.php:13
$filename
Filename to store logs.
Definition: Mem.php:10
const EVENT_HALT
Definition: Fred.php:20
$maxSize
Maximum number of messages to store (empty = unlimited).
Definition: Mem.php:8
$save
Number of logs to save.
Definition: Mem.php:9