Guest User

Untitled

a guest
Jun 18th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.53 KB | None | 0 0
  1. <?php
  2.  
  3. class DebugLog
  4. {
  5.     const DEBUG_FILE = '/tmp/debug.log';
  6.    
  7.     protected static $_instance;
  8.    
  9.     protected $_handle = NULL;
  10.    
  11.     protected function __construct() {
  12.         $this->_handle = fopen($this::DEBUG_FILE, 'a+');
  13.        
  14.         if ($this->_handle === FALSE) {
  15.             throw new Exception('Failed to open debug log!');
  16.         }
  17.     }
  18.    
  19.     public function __destruct() {
  20.         //fclose($this->_handle);
  21.     }
  22.    
  23.     public static function getInstance() {
  24.         if(!self::$_instance instanceof self) {
  25.             self::$_instance = new self();
  26.         }
  27.        
  28.         return self::$_instance;
  29.     }
  30.    
  31.     public function log($msg, $tag='')
  32.     {
  33.         // retrieve the backtrace and set the file & line
  34.         $backtrace = debug_backtrace();
  35.        
  36.         $formattedBacktrace = '';
  37.         foreach ($backtrace as $i=>$entry) {
  38.             $formattedBacktrace.= sprintf('#%-2d | %-4s | %-30s | %s'. PHP_EOL, $i, $entry['line'], $entry['function'], $entry['file']);
  39.         }
  40.        
  41.         // get the currently formatted time
  42.         $time = date('Ymd H:i:s');
  43.    
  44.         // format the tags
  45.         if (!empty($tag)) {
  46.             if (is_array($tag)) {
  47.                 $tag = implode(',', $tag);
  48.             }
  49.         }
  50.    
  51.         // format the start line
  52.         $preamble = sprintf('-------------- %s tags(%s) --------------', $time, $tag);
  53.        
  54.         // format the message
  55.         if (is_array($msg) || is_object($msg)) {
  56.             $msg = print_r($msg, TRUE);
  57.         }
  58.        
  59.         $hr = '----------';
  60.        
  61.         // log the message
  62.         if (fwrite($this->_handle, $preamble. PHP_EOL. $msg. PHP_EOL. $hr. PHP_EOL. $formattedBacktrace) === FALSE) {
  63.             throw new Exception('Failed to write to debug log.');
  64.         }
  65.        
  66.         return $this;
  67.     }
  68.    
  69. }
Add Comment
Please, Sign In to add comment