Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770
Форумы портала PHP.SU :: Версия для печати :: Класс для ведения логов
Форумы портала PHP.SU » PHP » Пользовательские функции » Класс для ведения логов

Страниц (1): [1]
 

1. White - 20 Июня, 2011 - 22:11:26 - перейти к сообщению
Возможно кому то пригодится, написано мной для ведения логов SQL запросов, но возможности применения значительно шире.
В начале кроткое API

CODE (htmlphp):
скопировать код в буфер обмена
  1.  
  2. <?php
  3. /* Multypurpose logger class v1.0.0
  4.  * ### Functions ###
  5.  *              $log = log::start([$die_limit, $log_url, $log_ip, $log_time])
  6.  *                      Starts logger, arguments are optional and should be sent on first init,
  7.  *                      any further attempts will be ignored.
  8.  *                      If using inside functions $log = log::start should be called to get an access to object
  9.  *                      ### Arguments ###
  10.  *                      $die_limit - maximum rows in logger, if reached will cause script break (defaults to 0)
  11.  *                      $log_url - if set to 0, will not log url
  12.  *                      $log_ip - if set to 0, will not log ip
  13.  *                      $log_time - if set to 0, will not log time
  14.  *              $log->add($string)
  15.  *                      Adds new entry to logger with $string text
  16.  *              $log->build([$type])
  17.  *                      Returns log in string
  18.  *                      ### Arguments ###
  19.  *                      $type = ('html' || 'text' || 'plain'), defaults to 'html'
  20.  *                              'html' - build log as html table
  21.  *                              'text' - build as a text
  22.  *                              'plain' - build as serialized object string
  23.  *              $log->show([$row])
  24.  *                      Returns an object with parameters for $row(defaults to last string)
  25.  *                      $row - is a $row number to show
  26.  *                              returns $obj->string(entry text), [$obj->url, $obj->ip, $obj->time]*if set
  27.  *              $log->write($filename [, $type, $rewrite])
  28.  *                      Writes data to file ($filename)
  29.  *                      ### Arguments ###
  30.  *                      $type - ('html', 'text', 'plain') same as for build
  31.  *                      $rewrite - bool, if set will not append, but rewrite file
  32.  *
  33.  * Under condition and terms of GNU/GPL
  34.  * 2011, Oleg Kasian, o-kasian@yandex.ru
  35.  */
  36.  
  37. class log {
  38.        private $die_limit;
  39.        private $log_time;
  40.        private $log_ip;
  41.        private $log_url;
  42.        private $counter;
  43.        private $row;
  44.   private static $instance;
  45.  
  46.   private function __construct($die_limit, $log_time, $log_ip, $log_url) {
  47.                $this->die_limit=$die_limit;
  48.                $this->log_time=$log_time;
  49.                $this->log_ip=$log_ip;
  50.                $this->log_url=$log_url;
  51.                $this->counter=0;
  52.        }
  53.      
  54.   public function __clone() {}
  55.      
  56. //typical singleton construction function
  57.        public static function start($die_limit=0, $log_url=1, $log_ip=1, $log_time=1) {
  58.       if (!isset(self::$instance)) {
  59.           $c = __CLASS__;
  60.           self::$instance = new $c($die_limit, $log_time, $log_ip, $log_url);
  61.       }
  62.       return self::$instance;
  63.   }
  64.              
  65. //adds new string to log, any string to log must be set as an argument
  66.        public function add($string) {
  67.                $this->row[$this->counter]->string = $string;
  68.                if($this->log_url) $this->row[$this->counter]->url = $_SERVER["REQUEST_URI"];
  69.                if($this->log_ip) $this->row[$this->counter]->ip = $_SERVER['REMOTE_ADDR'];
  70.                if($this->log_time) $this->row[$this->counter]->time = time();
  71.                ++$this->counter;
  72.                $this->limit();
  73.        }
  74.  
  75. //builds log to str, argument(optional) $type=('html' || 'text' || 'plain')
  76.        public function build($type='html') {
  77.                switch(strtolower($type)) {
  78.                        case 'html':
  79.                                $output = '<h3>Site Log</h3><table style="width:100%" id="site_log">';
  80.                                $output .= '<tr><td><b>Text</b></td>';
  81.                                if($this->log_url) $output .= '<td><b>Url</b></td>';
  82.                                if($this->log_ip) $output .= '<td><b>Ip</b></td>';
  83.                                if($this->log_time) $output .= '<td><b>Time</b></td>';
  84.                                $output .= '</tr>';
  85.                                foreach($this->row as $value) {
  86.                                        $output .= '<tr><td>'.$value->string.'</td>';
  87.                                        if($this->log_url) $output .= '<td>'.($value->url).'</td>';
  88.                                        if($this->log_ip) $output .= '<td>'.($value->ip).'</td>';
  89.                                        if($this->log_time) $output .= '<td>'.date('r', $value->time).'</td>';
  90.                                        $output .= '</tr>';
  91.                                }
  92.                                $output .= '</table>';
  93.                        break;
  94.                        case 'text':
  95.                                foreach($this->row as $value) {
  96.                                        $output .= $value->string.' called';
  97.                                        if($this->log_url) $output .= ' at '.$value->url;
  98.                                        if($this->log_ip) $output .= ' by '.$value->ip;
  99.                                        if($this->log_time) $output .= ' time '.date('r', $value->time);
  100.                                        $output .= "\r\n";
  101.                                }
  102.                        break;
  103.                        case 'plain':
  104.                                        $output .= serialize($this->row);
  105.                        break;
  106.                        default:
  107.                                $output='bad argument for build: '.strtolower($type);
  108.                }
  109.                return $output;
  110.        }
  111.      
  112. //shows last row if no argument set, else shows row number $row(int value)
  113.        public function show($row='last') {
  114.                if(strtolower($row)=='last') {
  115.                        $output = $this->row[$this->counter-1];
  116.                } else {
  117.                        if((int)$row>($this->counter-1)) $output='no row exist'; else $output = $this->row[$row];
  118.                }
  119.                return $output;
  120.        }
  121.  
  122. //writes log to $file (local path must be set)
  123.        public function write($file, $type='text', $rewrite=0) {
  124.                if($rewrite) $fp = fopen($file, 'w'); else $fp = fopen($file, 'a');
  125.                fwrite($fp, $this->build($type));
  126.                fclose($fp);
  127.        }
  128.      
  129. //writes custom error message if limit is reached
  130.        private function limit() {
  131.                if($this->die_limit and $this->die_limit==$this->counter) {
  132.                        echo '<p style="display:block;color:red;background-color:yellow;border:1px solid red;">Log limit is reached. Will now stop.</p>';
  133.                        die();
  134.                }
  135.        }
  136. }
  137. ?>
  138.  
2. DeepVarvar - 20 Июня, 2011 - 23:11:56 - перейти к сообщению
Занятно. Закатив глазки
Если не сложно прикрепи в аттач к сообщению, ато слишком сложно копировать - лишние символы цепляет.

таб в восемь пробелов Подмигивание gedit или привычка??
У меня и то и то Радость
3. White - 21 Июня, 2011 - 07:55:53 - перейти к сообщению
Цитата:
таб в восемь пробелов gedit или привычка??
У меня и то и то


geany (по сути тот же gedit, но мне как то больше по душе) + привычка Закатив глазки

 

Powered by ExBB FM 1.0 RC1