PageRenderTime 51ms CodeModel.GetById 20ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/zf/library/Zend/Log.php

http://github.com/eryx/php-framework-benchmark
PHP | 624 lines | 314 code | 69 blank | 241 comment | 50 complexity | 0f18f87bed23c63b56ca31cef610f02a MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, Apache-2.0, LGPL-2.1, LGPL-3.0, BSD-2-Clause
  1<?php
  2/**
  3 * Zend Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the new BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 * It is also available through the world-wide-web at this URL:
 10 * http://framework.zend.com/license/new-bsd
 11 * If you did not receive a copy of the license and are unable to
 12 * obtain it through the world-wide-web, please send an email
 13 * to license@zend.com so we can send you a copy immediately.
 14 *
 15 * @category   Zend
 16 * @package    Zend_Log
 17 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 18 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 19 * @version    $Id: Log.php 23783 2011-03-01 21:47:35Z intiilapa $
 20 */
 21
 22/**
 23 * @category   Zend
 24 * @package    Zend_Log
 25 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 26 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 27 * @version    $Id: Log.php 23783 2011-03-01 21:47:35Z intiilapa $
 28 */
 29class Zend_Log
 30{
 31    const EMERG   = 0;  // Emergency: system is unusable
 32    const ALERT   = 1;  // Alert: action must be taken immediately
 33    const CRIT    = 2;  // Critical: critical conditions
 34    const ERR     = 3;  // Error: error conditions
 35    const WARN    = 4;  // Warning: warning conditions
 36    const NOTICE  = 5;  // Notice: normal but significant condition
 37    const INFO    = 6;  // Informational: informational messages
 38    const DEBUG   = 7;  // Debug: debug messages
 39
 40    /**
 41     * @var array of priorities where the keys are the
 42     * priority numbers and the values are the priority names
 43     */
 44    protected $_priorities = array();
 45
 46    /**
 47     * @var array of Zend_Log_Writer_Abstract
 48     */
 49    protected $_writers = array();
 50
 51    /**
 52     * @var array of Zend_Log_Filter_Interface
 53     */
 54    protected $_filters = array();
 55
 56    /**
 57     * @var array of extra log event
 58     */
 59    protected $_extras = array();
 60
 61    /**
 62     *
 63     * @var string
 64     */
 65    protected $_defaultWriterNamespace = 'Zend_Log_Writer';
 66
 67    /**
 68     *
 69     * @var string
 70     */
 71    protected $_defaultFilterNamespace = 'Zend_Log_Filter';
 72
 73    /**
 74     *
 75     * @var string
 76     */
 77    protected $_defaultFormatterNamespace = 'Zend_Log_Formatter';
 78
 79    /**
 80     *
 81     * @var callback
 82     */
 83    protected $_origErrorHandler       = null;
 84
 85    /**
 86     *
 87     * @var boolean
 88     */
 89    protected $_registeredErrorHandler = false;
 90
 91    /**
 92     *
 93     * @var array|boolean
 94     */
 95    protected $_errorHandlerMap        = false;
 96
 97    /**
 98     *
 99     * @var string
100     */
101    protected $_timestampFormat        = 'c';
102
103    /**
104     * Class constructor.  Create a new logger
105     *
106     * @param Zend_Log_Writer_Abstract|null  $writer  default writer
107     * @return void
108     */
109    public function __construct(Zend_Log_Writer_Abstract $writer = null)
110    {
111        $r = new ReflectionClass($this);
112        $this->_priorities = array_flip($r->getConstants());
113
114        if ($writer !== null) {
115            $this->addWriter($writer);
116        }
117    }
118
119    /**
120     * Factory to construct the logger and one or more writers
121     * based on the configuration array
122     *
123     * @param  array|Zend_Config Array or instance of Zend_Config
124     * @return Zend_Log
125     * @throws Zend_Log_Exception
126     */
127    static public function factory($config = array())
128    {
129        if ($config instanceof Zend_Config) {
130            $config = $config->toArray();
131        }
132
133        if (!is_array($config) || empty($config)) {
134            /** @see Zend_Log_Exception */
135            require_once 'Zend/Log/Exception.php';
136            throw new Zend_Log_Exception('Configuration must be an array or instance of Zend_Config');
137        }
138
139        $log = new self;
140
141        if (array_key_exists('timestampFormat', $config)) {
142            if (null != $config['timestampFormat'] && '' != $config['timestampFormat']) {
143                $log->setTimestampFormat($config['timestampFormat']);
144            }
145            unset($config['timestampFormat']);
146        }
147
148        if (!is_array(current($config))) {
149            $log->addWriter(current($config));
150        } else {
151            foreach($config as $writer) {
152                $log->addWriter($writer);
153            }
154        }
155
156        return $log;
157    }
158
159
160    /**
161     * Construct a writer object based on a configuration array
162     *
163     * @param  array $spec config array with writer spec
164     * @return Zend_Log_Writer_Abstract
165     * @throws Zend_Log_Exception
166     */
167    protected function _constructWriterFromConfig($config)
168    {
169        $writer = $this->_constructFromConfig('writer', $config, $this->_defaultWriterNamespace);
170
171        if (!$writer instanceof Zend_Log_Writer_Abstract) {
172            $writerName = is_object($writer)
173                        ? get_class($writer)
174                        : 'The specified writer';
175            /** @see Zend_Log_Exception */
176            require_once 'Zend/Log/Exception.php';
177            throw new Zend_Log_Exception("{$writerName} does not extend Zend_Log_Writer_Abstract!");
178        }
179
180        if (isset($config['filterName'])) {
181            $filter = $this->_constructFilterFromConfig($config);
182            $writer->addFilter($filter);
183        }
184
185        if (isset($config['formatterName'])) {
186            $formatter = $this->_constructFormatterFromConfig($config);
187            $writer->setFormatter($formatter);
188        }
189
190        return $writer;
191    }
192
193    /**
194     * Construct filter object from configuration array or Zend_Config object
195     *
196     * @param  array|Zend_Config $config Zend_Config or Array
197     * @return Zend_Log_Filter_Interface
198     * @throws Zend_Log_Exception
199     */
200    protected function _constructFilterFromConfig($config)
201    {
202        $filter = $this->_constructFromConfig('filter', $config, $this->_defaultFilterNamespace);
203
204        if (!$filter instanceof Zend_Log_Filter_Interface) {
205             $filterName = is_object($filter)
206                         ? get_class($filter)
207                         : 'The specified filter';
208            /** @see Zend_Log_Exception */
209            require_once 'Zend/Log/Exception.php';
210            throw new Zend_Log_Exception("{$filterName} does not implement Zend_Log_Filter_Interface");
211        }
212
213        return $filter;
214    }
215
216   /**
217     * Construct formatter object from configuration array or Zend_Config object
218     *
219     * @param  array|Zend_Config $config Zend_Config or Array
220     * @return Zend_Log_Formatter_Interface
221     * @throws Zend_Log_Exception
222     */
223    protected function _constructFormatterFromConfig($config)
224    {
225        $formatter = $this->_constructFromConfig('formatter', $config, $this->_defaultFormatterNamespace);
226
227        if (!$formatter instanceof Zend_Log_Formatter_Interface) {
228             $formatterName = is_object($formatter)
229                         ? get_class($formatter)
230                         : 'The specified formatter';
231            /** @see Zend_Log_Exception */
232            require_once 'Zend/Log/Exception.php';
233            throw new Zend_Log_Exception($formatterName . ' does not implement Zend_Log_Formatter_Interface');
234        }
235
236        return $formatter;
237    }
238
239    /**
240     * Construct a filter or writer from config
241     *
242     * @param string $type 'writer' of 'filter'
243     * @param mixed $config Zend_Config or Array
244     * @param string $namespace
245     * @return object
246     * @throws Zend_Log_Exception
247     */
248    protected function _constructFromConfig($type, $config, $namespace)
249    {
250        if ($config instanceof Zend_Config) {
251            $config = $config->toArray();
252        }
253
254        if (!is_array($config) || empty($config)) {
255            require_once 'Zend/Log/Exception.php';
256            throw new Zend_Log_Exception(
257                'Configuration must be an array or instance of Zend_Config'
258            );
259        }
260
261        $params    = isset($config[ $type .'Params' ]) ? $config[ $type .'Params' ] : array();
262        $className = $this->getClassName($config, $type, $namespace);
263        if (!class_exists($className)) {
264            require_once 'Zend/Loader.php';
265            Zend_Loader::loadClass($className);
266        }
267
268        $reflection = new ReflectionClass($className);
269        if (!$reflection->implementsInterface('Zend_Log_FactoryInterface')) {
270            require_once 'Zend/Log/Exception.php';
271            throw new Zend_Log_Exception(
272                $className . ' does not implement Zend_Log_FactoryInterface and can not be constructed from config.'
273            );
274        }
275
276        return call_user_func(array($className, 'factory'), $params);
277    }
278
279    /**
280     * Get the writer or filter full classname
281     *
282     * @param array $config
283     * @param string $type filter|writer
284     * @param string $defaultNamespace
285     * @return string full classname
286     * @throws Zend_Log_Exception
287     */
288    protected function getClassName($config, $type, $defaultNamespace)
289    {
290        if (!isset($config[ $type . 'Name' ])) {
291            require_once 'Zend/Log/Exception.php';
292            throw new Zend_Log_Exception("Specify {$type}Name in the configuration array");
293        }
294        $className = $config[ $type . 'Name' ];
295
296        $namespace = $defaultNamespace;
297        if (isset($config[ $type . 'Namespace' ])) {
298            $namespace = $config[ $type . 'Namespace' ];
299        }
300
301        $fullClassName = $namespace . '_' . $className;
302        return $fullClassName;
303    }
304
305    /**
306     * Packs message and priority into Event array
307     *
308     * @param  string   $message   Message to log
309     * @param  integer  $priority  Priority of message
310     * @return array Event array
311     */
312    protected function _packEvent($message, $priority)
313    {
314        return array_merge(array(
315            'timestamp'    => date($this->_timestampFormat),
316            'message'      => $message,
317            'priority'     => $priority,
318            'priorityName' => $this->_priorities[$priority]
319            ),
320            $this->_extras
321        );
322    }
323
324    /**
325     * Class destructor.  Shutdown log writers
326     *
327     * @return void
328     */
329    public function __destruct()
330    {
331        foreach($this->_writers as $writer) {
332            $writer->shutdown();
333        }
334    }
335
336    /**
337     * Undefined method handler allows a shortcut:
338     *   $log->priorityName('message')
339     *     instead of
340     *   $log->log('message', Zend_Log::PRIORITY_NAME)
341     *
342     * @param  string  $method  priority name
343     * @param  string  $params  message to log
344     * @return void
345     * @throws Zend_Log_Exception
346     */
347    public function __call($method, $params)
348    {
349        $priority = strtoupper($method);
350        if (($priority = array_search($priority, $this->_priorities)) !== false) {
351            switch (count($params)) {
352                case 0:
353                    /** @see Zend_Log_Exception */
354                    require_once 'Zend/Log/Exception.php';
355                    throw new Zend_Log_Exception('Missing log message');
356                case 1:
357                    $message = array_shift($params);
358                    $extras = null;
359                    break;
360                default:
361                    $message = array_shift($params);
362                    $extras  = array_shift($params);
363                    break;
364            }
365            $this->log($message, $priority, $extras);
366        } else {
367            /** @see Zend_Log_Exception */
368            require_once 'Zend/Log/Exception.php';
369            throw new Zend_Log_Exception('Bad log priority');
370        }
371    }
372
373    /**
374     * Log a message at a priority
375     *
376     * @param  string   $message   Message to log
377     * @param  integer  $priority  Priority of message
378     * @param  mixed    $extras    Extra information to log in event
379     * @return void
380     * @throws Zend_Log_Exception
381     */
382    public function log($message, $priority, $extras = null)
383    {
384        // sanity checks
385        if (empty($this->_writers)) {
386            /** @see Zend_Log_Exception */
387            require_once 'Zend/Log/Exception.php';
388            throw new Zend_Log_Exception('No writers were added');
389        }
390
391        if (! isset($this->_priorities[$priority])) {
392            /** @see Zend_Log_Exception */
393            require_once 'Zend/Log/Exception.php';
394            throw new Zend_Log_Exception('Bad log priority');
395        }
396
397        // pack into event required by filters and writers
398        $event = $this->_packEvent($message, $priority);
399
400        // Check to see if any extra information was passed
401        if (!empty($extras)) {
402            $info = array();
403            if (is_array($extras)) {
404                foreach ($extras as $key => $value) {
405                    if (is_string($key)) {
406                        $event[$key] = $value;
407                    } else {
408                        $info[] = $value;
409                    }
410                }
411            } else {
412                $info = $extras;
413            }
414            if (!empty($info)) {
415                $event['info'] = $info;
416            }
417        }
418
419        // abort if rejected by the global filters
420        foreach ($this->_filters as $filter) {
421            if (! $filter->accept($event)) {
422                return;
423            }
424        }
425
426        // send to each writer
427        foreach ($this->_writers as $writer) {
428            $writer->write($event);
429        }
430    }
431
432    /**
433     * Add a custom priority
434     *
435     * @param  string   $name      Name of priority
436     * @param  integer  $priority  Numeric priority
437     * @throws Zend_Log_Exception
438     */
439    public function addPriority($name, $priority)
440    {
441        // Priority names must be uppercase for predictability.
442        $name = strtoupper($name);
443
444        if (isset($this->_priorities[$priority])
445            || false !== array_search($name, $this->_priorities)) {
446            /** @see Zend_Log_Exception */
447            require_once 'Zend/Log/Exception.php';
448            throw new Zend_Log_Exception('Existing priorities cannot be overwritten');
449        }
450
451        $this->_priorities[$priority] = $name;
452        return $this;
453    }
454
455    /**
456     * Add a filter that will be applied before all log writers.
457     * Before a message will be received by any of the writers, it
458     * must be accepted by all filters added with this method.
459     *
460     * @param  int|Zend_Config|array|Zend_Log_Filter_Interface $filter
461     * @return Zend_Log
462     * @throws Zend_Log_Exception
463     */
464    public function addFilter($filter)
465    {
466        if (is_int($filter)) {
467            /** @see Zend_Log_Filter_Priority */
468            require_once 'Zend/Log/Filter/Priority.php';
469            $filter = new Zend_Log_Filter_Priority($filter);
470
471        } elseif ($filter instanceof Zend_Config || is_array($filter)) {
472            $filter = $this->_constructFilterFromConfig($filter);
473
474        } elseif(! $filter instanceof Zend_Log_Filter_Interface) {
475            /** @see Zend_Log_Exception */
476            require_once 'Zend/Log/Exception.php';
477            throw new Zend_Log_Exception('Invalid filter provided');
478        }
479
480        $this->_filters[] = $filter;
481        return $this;
482    }
483
484    /**
485     * Add a writer.  A writer is responsible for taking a log
486     * message and writing it out to storage.
487     *
488     * @param  mixed $writer Zend_Log_Writer_Abstract or Config array
489     * @return Zend_Log
490     */
491    public function addWriter($writer)
492    {
493        if (is_array($writer) || $writer instanceof  Zend_Config) {
494            $writer = $this->_constructWriterFromConfig($writer);
495        }
496
497        if (!$writer instanceof Zend_Log_Writer_Abstract) {
498            /** @see Zend_Log_Exception */
499            require_once 'Zend/Log/Exception.php';
500            throw new Zend_Log_Exception(
501                'Writer must be an instance of Zend_Log_Writer_Abstract'
502                . ' or you should pass a configuration array'
503            );
504        }
505
506        $this->_writers[] = $writer;
507        return $this;
508    }
509
510    /**
511     * Set an extra item to pass to the log writers.
512     *
513     * @param  string $name    Name of the field
514     * @param  string $value   Value of the field
515     * @return Zend_Log
516     */
517    public function setEventItem($name, $value)
518    {
519        $this->_extras = array_merge($this->_extras, array($name => $value));
520        return $this;
521    }
522
523    /**
524     * Register Logging system as an error handler to log php errors
525     * Note: it still calls the original error handler if set_error_handler is able to return it.
526     *
527     * Errors will be mapped as:
528     *   E_NOTICE, E_USER_NOTICE => NOTICE
529     *   E_WARNING, E_CORE_WARNING, E_USER_WARNING => WARN
530     *   E_ERROR, E_USER_ERROR, E_CORE_ERROR, E_RECOVERABLE_ERROR => ERR
531     *   E_DEPRECATED, E_STRICT, E_USER_DEPRECATED => DEBUG
532     *   (unknown/other) => INFO
533     *
534     * @link http://www.php.net/manual/en/function.set-error-handler.php Custom error handler
535     *
536     * @return Zend_Log
537     */
538    public function registerErrorHandler()
539    {
540        // Only register once.  Avoids loop issues if it gets registered twice.
541        if ($this->_registeredErrorHandler) {
542            return $this;
543        }
544
545        $this->_origErrorHandler = set_error_handler(array($this, 'errorHandler'));
546
547        // Contruct a default map of phpErrors to Zend_Log priorities.
548        // Some of the errors are uncatchable, but are included for completeness
549        $this->_errorHandlerMap = array(
550            E_NOTICE            => Zend_Log::NOTICE,
551            E_USER_NOTICE       => Zend_Log::NOTICE,
552            E_WARNING           => Zend_Log::WARN,
553            E_CORE_WARNING      => Zend_Log::WARN,
554            E_USER_WARNING      => Zend_Log::WARN,
555            E_ERROR             => Zend_Log::ERR,
556            E_USER_ERROR        => Zend_Log::ERR,
557            E_CORE_ERROR        => Zend_Log::ERR,
558            E_RECOVERABLE_ERROR => Zend_Log::ERR,
559            E_STRICT            => Zend_Log::DEBUG,
560        );
561        // PHP 5.3.0+
562        if (defined('E_DEPRECATED')) {
563            $this->_errorHandlerMap['E_DEPRECATED'] = Zend_Log::DEBUG;
564        }
565        if (defined('E_USER_DEPRECATED')) {
566            $this->_errorHandlerMap['E_USER_DEPRECATED'] = Zend_Log::DEBUG;
567        }
568
569        $this->_registeredErrorHandler = true;
570        return $this;
571    }
572
573    /**
574     * Error Handler will convert error into log message, and then call the original error handler
575     *
576     * @link http://www.php.net/manual/en/function.set-error-handler.php Custom error handler
577     * @param int $errno
578     * @param string $errstr
579     * @param string $errfile
580     * @param int $errline
581     * @param array $errcontext
582     * @return boolean
583     */
584    public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
585    {
586        $errorLevel = error_reporting();
587
588        if ($errorLevel && $errno) {
589            if (isset($this->_errorHandlerMap[$errno])) {
590                $priority = $this->_errorHandlerMap[$errno];
591            } else {
592                $priority = Zend_Log::INFO;
593            }
594            $this->log($errstr, $priority, array('errno'=>$errno, 'file'=>$errfile, 'line'=>$errline, 'context'=>$errcontext));
595        }
596
597        if ($this->_origErrorHandler !== null) {
598            return call_user_func($this->_origErrorHandler, $errno, $errstr, $errfile, $errline, $errcontext);
599        }
600        return false;
601    }
602
603    /**
604     * Set timestamp format for log entries.
605     *
606     * @param string $format
607     * @return Zend_Log
608     */
609    public function setTimestampFormat($format)
610    {
611        $this->_timestampFormat = $format;
612        return $this;
613    }
614
615    /**
616     * Get timestamp format used for log entries.
617     *
618     * @return string
619     */
620    public function getTimestampFormat()
621    {
622        return $this->_timestampFormat;
623    }
624}