PageRenderTime 16ms CodeModel.GetById 2ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 1ms

/trunk/BarBottin/lib/PEAR/docs/Log/docs/guide.txt

https://gitlab.com/BGCX261/zigolive-svn-to-git
Plain Text | 1090 lines | 863 code | 227 blank | 0 comment | 0 complexity | 6406c854f92550eaf294f9e1ee6e4c31 MD5 | raw file
   1=================
   2 The Log Package
   3=================
   4
   5--------------------
   6 User Documentation
   7--------------------
   8
   9:Author:        Jon Parise
  10:Contact:       jon@php.net
  11:Date:          $Date: 2007/02/09 05:32:48 $
  12:Revision:      $Revision: 1.32 $
  13
  14.. contents:: Contents
  15.. section-numbering::
  16
  17Using Log Handlers
  18==================
  19
  20The Log package is implemented as a framework that supports the notion of
  21backend-specific log handlers.  The base logging object (defined by the `Log
  22class`_) is primarily an abstract interface to the currently configured
  23handler.
  24
  25A wide variety of handlers are distributed with the Log package, and, should
  26none of them fit your application's needs, it's easy to `write your own`__.
  27
  28.. _Log class: http://cvs.php.net/co.php/pear/Log/Log.php
  29__ `Custom Handlers`_
  30
  31Creating a Log Object
  32---------------------
  33There are three ways to create Log objects:
  34
  35    - Using the ``Log::factory()`` method
  36    - Using the ``Log::singleton()`` method
  37    - Direct instantiation
  38
  39The Factory Method
  40~~~~~~~~~~~~~~~~~~
  41The ``Log::factory()`` method implements the `Factory Pattern`_.  It allows
  42for the parameterized construction of concrete Log instances at runtime.  The
  43first parameter to the ``Log::factory()`` method indicates the name of the
  44concrete handler to create.  The rest of the parameters will be passed on to
  45the handler's constructor (see `Configuring a Handler`_ below).
  46
  47The new ``Log`` instance is returned by reference.
  48
  49::
  50
  51    require_once 'Log.php';
  52
  53    $console = &Log::factory('console', '', 'TEST');
  54    $console->log('Logging to the console.');
  55
  56    $file = &Log::factory('file', 'out.log', 'TEST');
  57    $file->log('Logging to out.log.');
  58
  59.. _Factory Pattern: http://www.phppatterns.com/index.php/article/articleview/49/1/1/
  60
  61The Singleton Method
  62~~~~~~~~~~~~~~~~~~~~
  63The ``Log::singleton()`` method implements the `Singleton Pattern`_.  The
  64singleton pattern ensures that only a single instance of a given log type and
  65configuration is ever created.  This has two benefits: first, it prevents
  66duplicate ``Log`` instances from being constructed, and, second, it gives all
  67of your code access to the same ``Log`` instance.  The latter is especially
  68important when logging to files because only a single file handler will need
  69to be managed.
  70
  71The ``Log::singleton()`` method's parameters match the ``Log::factory()``
  72method.  The new ``Log`` instance is returned by reference.
  73
  74::
  75
  76    require_once 'Log.php';
  77
  78    /* Same construction parameters */
  79    $a = &Log::singleton('console', '', 'TEST');
  80    $b = &Log::singleton('console', '', 'TEST');
  81
  82    if ($a === $b) {
  83        echo '$a and $b point to the same Log instance.' . "\n";
  84    }
  85
  86    /* Different construction parameters */
  87    $c = &Log::singleton('console', '', 'TEST1');
  88    $d = &Log::singleton('console', '', 'TEST2');
  89
  90    if ($c !== $d) {
  91        echo '$c and $d point to different Log instances.' . "\n";
  92    }
  93
  94.. _Singleton Pattern: http://www.phppatterns.com/index.php/article/articleview/6/1/1/
  95
  96Direct Instantiation
  97~~~~~~~~~~~~~~~~~~~~
  98It is also possible to directly instantiate concrete ``Log`` handler
  99instances.  However, this method is **not recommended** because it creates a
 100tighter coupling between your application code and the Log package than is
 101necessary.  Use of `the factory method`_ or `the singleton method`_ is
 102preferred.
 103
 104
 105Configuring a Handler
 106---------------------
 107A log handler's configuration is determined by the arguments used in its
 108construction.  Here's an overview of those parameters::
 109
 110    /* Using the factory method ... */
 111    &Log::factory($handler, $name, $ident, $conf, $maxLevel);
 112
 113    /* Using the singleton method ... */
 114    &Log::singleton($handler, $name, $ident, $conf, $maxLevel);
 115
 116    /* Using direct instantiation ... */
 117    new Log_handler($name, $ident, $conf, $maxLevel);
 118
 119+---------------+-----------+-----------------------------------------------+
 120| Parameter     | Type      | Description                                   |
 121+===============+===========+===============================================+
 122| ``$handler``  | String    | The type of Log handler to construct.  This   |
 123|               |           | parameter is only available when `the factory |
 124|               |           | method`_ or `the singleton method`_ are used. |
 125+---------------+-----------+-----------------------------------------------+
 126| ``$name``     | String    | The name of the log resource to which the     |
 127|               |           | events will be logged.  The use of this value |
 128|               |           | is determined by the handler's implementation.|
 129|               |           | It defaults to an empty string.               |
 130+---------------+-----------+-----------------------------------------------+
 131| ``$ident``    | String    | An identification string that will be included|
 132|               |           | in all log events logged by this handler.     |
 133|               |           | This value defaults to an empty string and can|
 134|               |           | be changed at runtime using the ``setIdent()``|
 135|               |           | method.                                       |
 136+---------------+-----------+-----------------------------------------------+
 137| ``$conf``     | Array     | Associative array of key-value pairs that are |
 138|               |           | used to specify any handler-specific settings.|
 139+---------------+-----------+-----------------------------------------------+
 140| ``$level``    | Integer   | Log messages up to and including this level.  |
 141|               |           | This value defaults to ``PEAR_LOG_DEBUG``.    |
 142|               |           | See `Log Levels`_ and `Log Level Masks`_.     |
 143+---------------+-----------+-----------------------------------------------+
 144
 145
 146Logging an Event
 147----------------
 148Events are logged using the ``log()`` method::
 149
 150    $logger->log('Message', PEAR_LOG_NOTICE);
 151
 152The first argument contains the log event's message.  Even though the event is
 153always logged as a string, it is possible to pass an object to the ``log()``
 154method.  If the object implements a ``getString()`` method, a ``toString()``
 155method or Zend Engine 2's special ``__toString()`` casting method, it will be
 156used to determine the object's string representation.  Otherwise, the
 157`serialized`_ form of the object will be logged.
 158
 159The second, optional argument specifies the log event's priority.  See the
 160`Log Levels`_ table for the complete list of priorities.  The default priority
 161is PEAR_LOG_INFO.
 162
 163The ``log()`` method will return ``true`` if the event was successfully
 164logged.
 165
 166"Shortcut" methods are also available for logging an event at a specific log
 167level.  See the `Log Levels`_ table for the complete list.
 168
 169.. _serialized: http://www.php.net/serialize
 170
 171
 172Log Levels
 173----------
 174This table is ordered by highest priority (``PEAR_LOG_EMERG``) to lowest
 175priority (``PEAR_LOG_DEBUG``).
 176
 177+-----------------------+---------------+-----------------------------------+
 178| Level                 | Shortcut      | Description                       |
 179+=======================+===============+===================================+
 180| ``PEAR_LOG_EMERG``    | ``emerg()``   | System is unusable                |
 181+-----------------------+---------------+-----------------------------------+
 182| ``PEAR_LOG_ALERT``    | ``alert()``   | Immediate action required         |
 183+-----------------------+---------------+-----------------------------------+
 184| ``PEAR_LOG_CRIT``     | ``crit()``    | Critical conditions               |
 185+-----------------------+---------------+-----------------------------------+
 186| ``PEAR_LOG_ERR``      | ``err()``     | Error conditions                  |
 187+-----------------------+---------------+-----------------------------------+
 188| ``PEAR_LOG_WARNING``  | ``warning()`` | Warning conditions                |
 189+-----------------------+---------------+-----------------------------------+
 190| ``PEAR_LOG_NOTICE``   | ``notice()``  | Normal but significant            |
 191+-----------------------+---------------+-----------------------------------+
 192| ``PEAR_LOG_INFO``     | ``info()``    | Informational                     |
 193+-----------------------+---------------+-----------------------------------+
 194| ``PEAR_LOG_DEBUG``    | ``debug()``   | Debug-level messages              |
 195+-----------------------+---------------+-----------------------------------+
 196
 197
 198Log Level Masks
 199---------------
 200Defining a log level mask allows you to include and/or exclude specific levels
 201of events from being logged.  The ``$level`` construction parameter (see
 202`Configuring a Handler`_) uses this mechanism to exclude log events below a
 203certain priority, and it's possible to define more complex masks once the Log
 204object has been constructed.
 205
 206Each priority has a specific mask associated with it.  To compute a priority's
 207mask, use the static ``Log::MASK()`` method::
 208
 209    $mask = Log::MASK(PEAR_LOG_INFO);
 210
 211To compute the mask for all priorities up to, and including, a certain level,
 212use the ``Log::MAX()`` static method::
 213
 214    $mask = Log::MAX(PEAR_LOG_INFO);
 215
 216To compute the mask for all priorities greater than or equal to a certain
 217level, use the ``Log::MIN()`` static method::
 218
 219    $mask = Log::MIN(PEAR_LOG_INFO);
 220
 221The apply the mask, use the ``setMask()`` method::
 222
 223    $logger->setMask($mask);
 224
 225Masks can be be combined using bitwise operations.  To restrict logging to
 226only those events marked as ``PEAR_LOG_NOTICE`` or ``PEAR_LOG_DEBUG``::
 227
 228    $mask = Log::MASK(PEAR_LOG_NOTICE) | Log::MASK(PEAR_LOG_DEBUG);
 229    $logger->setMask($mask);
 230
 231For convenience, two special masks are predefined: ``PEAR_LOG_NONE`` and
 232``PEAR_LOG_ALL``.  ``PEAR_LOG_ALL`` is especially useful for exluding only
 233specific priorities::
 234
 235    $mask = PEAR_LOG_ALL ^ Log::MASK(PEAR_LOG_NOTICE);
 236    $logger->setMask($mask);
 237
 238It is also possible to retrieve and modify a Log object's existing mask::
 239
 240    $mask = $logger->getMask() | Log::MASK(PEAR_LOG_INFO);
 241    $logger->setMask($mask);
 242
 243
 244Flushing Log Events
 245-------------------
 246Some log handlers (such as `the console handler`_) support explicit
 247"buffering".  When buffering is enabled, log events won't actually be written
 248to the output stream until the handler is closed.  Other handlers (such as
 249`the file handler`_) support implicit buffering because they use the operating
 250system's IO routines, which may buffer the output.
 251
 252It's possible to force these handlers to flush their output, however, by
 253calling their ``flush()`` method::
 254
 255    $conf = array('buffering' => true);
 256    $logger = &Log::singleton('console', '', 'test', $conf);
 257
 258    for ($i = 0; $i < 10; $i++) {
 259        $logger->log('This event will be buffered.');
 260    }
 261
 262    /* Flush all of the buffered log events. */
 263    $logger->flush();
 264
 265    for ($i = 0; $i < 10; $i++) {
 266        $logger->log('This event will be buffered.');
 267    }
 268
 269    /* Implicitly flush the buffered events on close. */
 270    $logger->close();
 271
 272At this time, the ``flush()`` method is only implemented by `the console
 273handler`_, `the file handler`_ and `the mail handler`_.
 274
 275
 276Standard Log Handlers
 277=====================
 278
 279The Console Handler
 280-------------------
 281The Console handler outputs log events directly to the console.  It supports
 282output buffering and configurable string formats.
 283
 284Configuration
 285~~~~~~~~~~~~~
 286+-------------------+-----------+---------------+---------------------------+
 287| Parameter         | Type      | Default       | Description               |
 288+===================+===========+===============+===========================+
 289| ``stream``        | File      | STDOUT_       | The output stream to use. |
 290+-------------------+-----------+---------------+---------------------------+
 291| ``buffering``     | Boolean   | False         | Should the output be      |
 292|                   |           |               | buffered until shutdown?  |
 293+-------------------+-----------+---------------+---------------------------+
 294| ``lineFormat``    | String    | ``%1$s %2$s   | Log line format           |
 295|                   |           | [%3$s] %4$s`` | specification.            |
 296+-------------------+-----------+---------------+---------------------------+
 297| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
 298|                   |           | %H:%M:%S``    | (for strftime_).          |
 299+-------------------+-----------+---------------+---------------------------+
 300
 301.. _STDOUT: http://www.php.net/wrappers.php
 302.. _strftime: http://www.php.net/strftime
 303
 304Example
 305~~~~~~~
 306::
 307
 308    $logger = &Log::singleton('console', '', 'ident');
 309    for ($i = 0; $i < 10; $i++) {
 310        $logger->log("Log entry $i");
 311    }
 312
 313
 314The Display Handler
 315-------------------
 316The Display handler simply prints the log events back to the browser.  It
 317respects the ``error_prepend_string`` and ``error_append_string`` `error
 318handling values`_ and is useful when `logging from standard error handlers`_.
 319
 320Configuration
 321~~~~~~~~~~~~~
 322+-------------------+-----------+---------------+---------------------------+
 323| Parameter         | Type      | Default       | Description               |
 324+===================+===========+===============+===========================+
 325| ``error_prepend`` | String    | PHP INI value | This string will be       |
 326|                   |           |               | prepended to the log      |
 327|                   |           |               | output.                   |
 328+-------------------+-----------+---------------+---------------------------+
 329| ``error_append``  | String    | PHP INI value | This string will be       |
 330|                   |           |               | appended to the log       |
 331|                   |           |               | output.                   |
 332+-------------------+-----------+---------------+---------------------------+
 333| ``linebreak``     | String    | ``<br />\n``  | This string is used to    |
 334|                   |           |               | represent a line break.   |
 335+-------------------+-----------+---------------+---------------------------+
 336
 337.. _error handling values: http://www.php.net/errorfunc
 338
 339Example
 340~~~~~~~
 341::
 342
 343    $conf = array('error_prepend' => '<font color="#ff0000"><tt>',
 344                  'error_append'  => '</tt></font>');
 345    $logger = &Log::singleton('display', '', '', $conf, PEAR_LOG_DEBUG);
 346    for ($i = 0; $i < 10; $i++) {
 347        $logger->log("Log entry $i");
 348    }
 349
 350
 351The Error_Log Handler
 352---------------------
 353The Error_Log handler sends log events to PHP's `error_log()`_ function.
 354
 355Configuration
 356~~~~~~~~~~~~~
 357+-------------------+-----------+---------------+---------------------------+
 358| Parameter         | Type      | Default       | Description               |
 359+===================+===========+===============+===========================+
 360| ``destination``   | String    | '' `(empty)`  | Optional destination value|
 361|                   |           |               | for `error_log()`_.  See  |
 362|                   |           |               | `Error_Log Types`_ for    |
 363|                   |           |               | more details.             |
 364+-------------------+-----------+---------------+---------------------------+
 365| ``extra_headers`` | String    | '' `(empty)`  | Additional headers to pass|
 366|                   |           |               | to the `mail()`_ function |
 367|                   |           |               | when the                  |
 368|                   |           |               | ``PEAR_LOG_TYPE_MAIL``    |
 369|                   |           |               | type is specified.        |
 370+-------------------+-----------+---------------+---------------------------+
 371
 372Error_Log Types
 373~~~~~~~~~~~~~~~
 374All of the available log types are detailed in the `error_log()`_ section of
 375the PHP manual.  For your convenience, the Log package also defines the
 376following constants that can be used for the ``$name`` handler construction
 377parameter.
 378
 379+---------------------------+-----------------------------------------------+
 380| Constant                  | Description                                   |
 381+===========================+===============================================+
 382| ``PEAR_LOG_TYPE_SYSTEM``  | Log events are sent to PHP's system logger,   |
 383|                           | which uses the operating system's logging     |
 384|                           | mechanism or a file (depending on the value   |
 385|                           | of the `error_log configuration directive`_). |
 386+---------------------------+-----------------------------------------------+
 387| ``PEAR_LOG_TYPE_MAIL``    | Log events are sent via email to the address  |
 388|                           | specified in the ``destination`` value.       |
 389+---------------------------+-----------------------------------------------+
 390| ``PEAR_LOG_TYPE_DEBUG``   | Log events are sent through PHP's debugging   |
 391|                           | connection.  This will only work if           |
 392|                           | `remote debugging`_ has been enabled.  The    |
 393|                           | ``destination`` value is used to specify the  |
 394|                           | host name or IP address of the target socket. |
 395+---------------------------+-----------------------------------------------+
 396| ``PEAR_LOG_TYPE_FILE``    | Log events will be appended to the file named |
 397|                           | by the ``destination`` value.                 |
 398+---------------------------+-----------------------------------------------+
 399
 400.. _error_log(): http://www.php.net/error_log
 401.. _mail(): http://www.php.net/mail
 402.. _error_log configuration directive: http://www.php.net/errorfunc#ini.error-log
 403.. _remote debugging: http://www.php.net/install.configure#install.configure.enable-debugger
 404
 405Example
 406~~~~~~~
 407::
 408
 409    $logger = &Log::singleton('error_log', PEAR_LOG_TYPE_SYSTEM, 'ident');
 410    for ($i = 0; $i < 10; $i++) {
 411        $logger->log("Log entry $i");
 412    }
 413
 414
 415The File Handler
 416----------------
 417The File handler writes log events to a text file using configurable string
 418formats.
 419
 420Configuration
 421~~~~~~~~~~~~~
 422+-------------------+-----------+---------------+---------------------------+
 423| Parameter         | Type      | Default       | Description               |
 424+===================+===========+===============+===========================+
 425| ``append``        | Boolean   | True          | Should new log entries be |
 426|                   |           |               | append to an existing log |
 427|                   |           |               | file, or should the a new |
 428|                   |           |               | log file overwrite an     |
 429|                   |           |               | existing one?             |
 430+-------------------+-----------+---------------+---------------------------+
 431| ``locking``       | Boolean   | False         | Should advisory file      |
 432|                   |           |               | locking (using flock_) be |
 433|                   |           |               | used?                     |
 434+-------------------+-----------+---------------+---------------------------+
 435| ``mode``          | Integer   | 0644          | Octal representation of   |
 436|                   |           |               | the log file's permissions|
 437|                   |           |               | mode.                     |
 438+-------------------+-----------+---------------+---------------------------+
 439| ``dirmode``       | Integer   | 0755          | Octal representation of   |
 440|                   |           |               | the file permission mode  |
 441|                   |           |               | that will be used when    |
 442|                   |           |               | creating directories that |
 443|                   |           |               | do not already exist.     |
 444+-------------------+-----------+---------------+---------------------------+
 445| ``eol``           | String    | OS default    | The end-on-line character |
 446|                   |           |               | sequence.                 |
 447+-------------------+-----------+---------------+---------------------------+
 448| ``lineFormat``    | String    | ``%1$s %2$s   | Log line format           |
 449|                   |           | [%3$s] %4$s`` | specification.            |
 450+-------------------+-----------+---------------+---------------------------+
 451| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
 452|                   |           | %H:%M:%S``    | (for strftime_).          |
 453+-------------------+-----------+---------------+---------------------------+
 454
 455.. _flock: http://www.php.net/flock
 456.. _strftime: http://www.php.net/strftime
 457
 458The file handler will only attempt to set the ``mode`` value if it was
 459responsible for creating the file.
 460
 461Example
 462~~~~~~~
 463::
 464
 465    $conf = array('mode' => 0600, 'timeFormat' => '%X %x');
 466    $logger = &Log::singleton('file', 'out.log', 'ident', $conf);
 467    for ($i = 0; $i < 10; $i++) {
 468        $logger->log("Log entry $i");
 469    }
 470
 471
 472The Firebug Handler
 473-------------------
 474The Firebug handler outputs log events to the Firebug_ console. It supports
 475output buffering and configurable string formats.
 476
 477Configuration
 478~~~~~~~~~~~~~
 479+-------------------+-----------+---------------+---------------------------+
 480| Parameter         | Type      | Default       | Description               |
 481+===================+===========+===============+===========================+
 482| ``buffering``     | Boolean   | False         | Should the output be      |
 483|                   |           |               | buffered until shutdown?  |
 484+-------------------+-----------+---------------+---------------------------+
 485| ``lineFormat``    | String    | ``%2$s [%3$s] | Log line format           |
 486|                   |           | %4$s``        | specification.            |
 487+-------------------+-----------+---------------+---------------------------+
 488| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
 489|                   |           | %H:%M:%S``    | (for strftime_).          |
 490+-------------------+-----------+---------------+---------------------------+
 491
 492.. _Firebug: http://www.getfirebug.com/
 493.. _strftime: http://www.php.net/strftime
 494
 495Example
 496~~~~~~~
 497::
 498
 499    $logger = &Log::singleton('firebug', '', 'ident');
 500    for ($i = 0; $i < 10; $i++) {
 501        $logger->log("Log entry $i");
 502    }
 503
 504
 505The Mail Handler
 506----------------
 507The Mail handler aggregates a session's log events and sends them in the body
 508of an email message using PHP's `mail()`_ function.
 509
 510Multiple recipients can be specified by separating their email addresses with
 511commas in the ``$name`` construction parameter.
 512
 513Configuration
 514~~~~~~~~~~~~~
 515+-------------------+-----------+---------------+---------------------------+
 516| Parameter         | Type      | Default       | Description               |
 517+===================+===========+===============+===========================+
 518| ``from``          | String    | sendmail_from | Value for the message's   |
 519|                   |           | INI value     | ``From:`` header.         |
 520+-------------------+-----------+---------------+---------------------------+
 521| ``subject``       | String    | ``[Log_mail]  | Value for the message's   |
 522|                   |           | Log message`` | ``Subject:`` header.      |
 523+-------------------+-----------+---------------+---------------------------+
 524| ``preamble``      | String    | `` `(empty)`  | Preamble for the message. |
 525+-------------------+-----------+---------------+---------------------------+
 526| ``lineFormat``    | String    | ``%1$s %2$s   | Log line format           |
 527|                   |           | [%3$s] %4$s`` | specification.            |
 528+-------------------+-----------+---------------+---------------------------+
 529| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
 530|                   |           | %H:%M:%S``    | (for strftime_).          |
 531+-------------------+-----------+---------------+---------------------------+
 532
 533.. _mail(): http://www.php.net/mail
 534
 535Example
 536~~~~~~~
 537::
 538
 539    $conf = array('subject' => 'Important Log Events');
 540    $logger = &Log::singleton('mail', 'webmaster@example.com', 'ident', $conf);
 541    for ($i = 0; $i < 10; $i++) {
 542        $logger->log("Log entry $i");
 543    }
 544
 545
 546The MDB2 Handler
 547----------------
 548The MDB2 handler is similar to `the SQL (DB) handler`_, but instead of using
 549the PEAR DB package, it uses the `MDB2 database abstraction package`_.
 550
 551Configuration
 552~~~~~~~~~~~~~
 553+-------------------+-----------+---------------+---------------------------+
 554| Parameter         | Type      | Default       | Description               |
 555+===================+===========+===============+===========================+
 556| ``dsn``           | Mixed     | '' `(empty)`  | A `Data Source Name`_.    |
 557|                   |           |               | |required|                |
 558+-------------------+-----------+---------------+---------------------------+
 559| ``options``       | Array     | ``persistent``| An array of `MDB2`_       |
 560|                   |           |               | options.                  |
 561+-------------------+-----------+---------------+---------------------------+
 562| ``db``            | Object    | NULL          | An existing `MDB2`_       |
 563|                   |           |               | object.  If specified,    |
 564|                   |           |               | this object will be used, |
 565|                   |           |               | and ``dsn`` will be       |
 566|                   |           |               | ignored.                  |
 567+-------------------+-----------+---------------+---------------------------+
 568| ``sequence``      | String    | ``log_id``    | The name of the sequence  |
 569|                   |           |               | to use when generating    |
 570|                   |           |               | unique event IDs.   Under |
 571|                   |           |               | many databases, this will |
 572|                   |           |               | be used as the name of    |
 573|                   |           |               | the sequence table.       |
 574+-------------------+-----------+---------------+---------------------------+
 575| ``identLimit``    | Integer   | 16            | The maximum length of the |
 576|                   |           |               | ``ident`` string.         |
 577|                   |           |               | **Changing this value may |
 578|                   |           |               | require updates to the SQL|
 579|                   |           |               | schema, as well.**        |
 580+-------------------+-----------+---------------+---------------------------+
 581| ``singleton``     | Boolean   | false         | Is true, use a singleton  |
 582|                   |           |               | database object using     |
 583|                   |           |               | `MDB2::singleton()`_.     |
 584+-------------------+-----------+---------------+---------------------------+
 585
 586.. _MDB2: http://pear.php.net/package/MDB2
 587.. _MDB2 database abstraction package: MDB2_
 588.. _MDB2::singleton(): http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2.html#methodsingleton
 589
 590The Null Handler
 591----------------
 592The Null handler simply consumes log events (akin to sending them to
 593``/dev/null``).  `Log level masks`_ are respected, and the event will still be
 594sent to any registered `log observers`_.
 595
 596Example
 597~~~~~~~
 598::
 599
 600    $logger = &Log::singleton('null');
 601    for ($i = 0; $i < 10; $i++) {
 602        $logger->log("Log entry $i");
 603    }
 604
 605
 606The SQL (DB) Handler
 607--------------------
 608
 609The SQL handler sends log events to a database using `PEAR's DB abstraction
 610layer`_.
 611
 612**Note:** Due to the constraints of the default database schema, the SQL
 613handler limits the length of the ``$ident`` string to sixteen (16) characters.
 614This limit can be adjusted using the ``identLimit`` configuration parameter.
 615
 616The Log Table
 617~~~~~~~~~~~~~
 618The default SQL table used by this handler looks like this::
 619
 620    CREATE TABLE log_table (
 621        id          INT NOT NULL,
 622        logtime     TIMESTAMP NOT NULL,
 623        ident       CHAR(16) NOT NULL,
 624        priority    INT NOT NULL,
 625        message     VARCHAR(200),
 626        PRIMARY KEY (id)
 627    );
 628
 629This is the "lowest common denominator" that should work across all SQL
 630compliant database.  You may want to make database- or site-specific changes
 631to this schema to support your specific needs, however.  For example,
 632`PostgreSQL`_ users may prefer to use a ``TEXT`` type for the ``message``
 633field.
 634
 635.. _PostgreSQL: http://www.postgresql.org/
 636
 637Configuration
 638~~~~~~~~~~~~~
 639+-------------------+-----------+---------------+---------------------------+
 640| Parameter         | Type      | Default       | Description               |
 641+===================+===========+===============+===========================+
 642| ``dsn``           | Mixed     | '' `(empty)`  | A `Data Source Name`_.    |
 643|                   |           |               | |required|                |
 644+-------------------+-----------+---------------+---------------------------+
 645| ``sql``           | String    | |sql-default| | SQL insertion statement.  |
 646+-------------------+-----------+---------------+---------------------------+
 647| ``options``       | Array     | ``persistent``| An array of `DB`_ options.|
 648+-------------------+-----------+---------------+---------------------------+
 649| ``db``            | Object    | NULL          | An existing `DB`_ object. |
 650|                   |           |               | If specified, this object |
 651|                   |           |               | will be used, and ``dsn`` |
 652|                   |           |               | will be ignored.          |
 653+-------------------+-----------+---------------+---------------------------+
 654| ``sequence``      | String    | ``log_id``    | The name of the sequence  |
 655|                   |           |               | to use when generating    |
 656|                   |           |               | unique event IDs.   Under |
 657|                   |           |               | many databases, this will |
 658|                   |           |               | be used as the name of    |
 659|                   |           |               | the sequence table.       |
 660+-------------------+-----------+---------------+---------------------------+
 661| ``identLimit``    | Integer   | 16            | The maximum length of the |
 662|                   |           |               | ``ident`` string.         |
 663|                   |           |               | **Changing this value may |
 664|                   |           |               | require updates to the SQL|
 665|                   |           |               | schema, as well.**        |
 666+-------------------+-----------+---------------+---------------------------+
 667
 668The name of the database table to which the log entries will be written is
 669specified using the ``$name`` construction parameter (see `Configuring a
 670Handler`_).
 671
 672.. |sql-default| replace:: ``INSERT INTO $table (id, logtime, ident, priority, message) VALUES(?, CURRENT_TIMESTAMP, ?, ?, ?)``
 673
 674.. _DB: http://pear.php.net/package/DB
 675.. _PEAR's DB abstraction layer: DB_
 676.. _Data Source Name: http://pear.php.net/manual/en/package.database.db.intro-dsn.php
 677
 678Examples
 679~~~~~~~~
 680Using a `Data Source Name`_ to create a new database connection::
 681
 682    $conf = array('dsn' => 'pgsql://jon@localhost+unix/logs');
 683    $logger = &Log::singleton('sql', 'log_table', 'ident', $conf);
 684    for ($i = 0; $i < 10; $i++) {
 685        $logger->log("Log entry $i");
 686    }
 687
 688Using an existing `DB`_ object::
 689
 690    require_once 'DB.php';
 691    $db = &DB::connect('pgsql://jon@localhost+unix/logs');
 692
 693    $conf['db'] = $db;
 694    $logger = &Log::singleton('sql', 'log_table', 'ident', $conf);
 695    for ($i = 0; $i < 10; $i++) {
 696        $logger->log("Log entry $i");
 697    }
 698
 699
 700The Sqlite Handler
 701------------------
 702:Author:        Bertrand Mansion
 703:Contact:       bmansion@mamasam.com
 704
 705The Sqlite handler sends log events to an Sqlite database using the `native
 706PHP sqlite functions`_.
 707
 708It is faster than `the SQL (DB) handler`_ because requests are made directly
 709to the database without using an abstraction layer.  It is also interesting to
 710note that Sqlite database files can be moved, copied, and deleted on your
 711system just like any other files, which makes log management easier.  Last but
 712not least, using a database to log your events allows you to use SQL queries
 713to create reports and statistics.
 714
 715When using a database and logging a lot of events, it is recommended to split
 716the database into smaller databases.  This is allowed by Sqlite, and you can
 717later use the Sqlite `ATTACH`_ statement to query your log database files
 718globally.
 719
 720If the database does not exist when the log is opened, sqlite will try to
 721create it automatically. If the log table does not exist, it will also be
 722automatically created.  The table creation uses the following SQL request::
 723
 724    CREATE TABLE log_table (
 725        id          INTEGER PRIMARY KEY NOT NULL,
 726        logtime     NOT NULL,
 727        ident       CHAR(16) NOT NULL,
 728        priority    INT NOT NULL,
 729        message
 730    );
 731
 732Configuration
 733~~~~~~~~~~~~~
 734+-------------------+-----------+---------------+---------------------------+
 735| Parameter         | Type      | Default       | Description               |
 736+===================+===========+===============+===========================+
 737| ``filename``      | String    | '' `(empty)`  | Path to an Sqlite         |
 738|                   |           |               | database. |required|      |
 739+-------------------+-----------+---------------+---------------------------+
 740| ``mode``          | Integer   | 0666          | Octal mode used to open   |
 741|                   |           |               | the database.             |
 742+-------------------+-----------+---------------+---------------------------+
 743| ``persistent``    | Boolean   | false         | Use a persistent          |
 744|                   |           |               | connection.               |
 745+-------------------+-----------+---------------+---------------------------+
 746
 747An already opened database connection can also be passed as parameter instead
 748of the above configuration.  In this case, closing the database connection is
 749up to the user.
 750
 751.. _native PHP sqlite functions: http://www.php.net/sqlite
 752.. _ATTACH: http://www.sqlite.org/lang.html#attach
 753
 754Examples
 755~~~~~~~~
 756Using a configuration to create a new database connection::
 757
 758    $conf = array('filename' => 'log.db', 'mode' => 0666, 'persistent' => true);
 759    $logger =& Log::factory('sqlite', 'log_table', 'ident', $conf);
 760    $logger->log('logging an event', PEAR_LOG_WARNING);
 761
 762Using an existing connection::
 763
 764    $db = sqlite_open('log.db', 0666, $error);
 765    $logger =& Log::factory('sqlite', 'log_table', 'ident', $db);
 766    $logger->log('logging an event', PEAR_LOG_WARNING);
 767    sqlite_close($db);
 768
 769
 770The Syslog Handler
 771------------------
 772The Syslog handler sends log events to the system logging service (syslog on
 773Unix-like environments or the Event Log on Windows systems).  The events are
 774sent using PHP's `syslog()`_ function.
 775
 776Configuration
 777~~~~~~~~~~~~~
 778+-------------------+-----------+---------------+---------------------------+
 779| Parameter         | Type      | Default       | Description               |
 780+===================+===========+===============+===========================+
 781| ``inherit``       | Boolean   | false         | Inherit the current syslog|
 782|                   |           |               | connection for this       |
 783|                   |           |               | process, or start a new   |
 784|                   |           |               | one via `openlog()`_?     |
 785+-------------------+-----------+---------------+---------------------------+
 786
 787Facilities
 788~~~~~~~~~~
 789+-------------------+-------------------------------------------------------+
 790| Constant          | Category Description                                  |
 791+===================+=======================================================+
 792| ``LOG_AUTH``      | Security / authorization messages; ``LOG_AUTHPRIV`` is|
 793|                   | preferred on systems where it is defined.             |
 794+-------------------+-------------------------------------------------------+
 795| ``LOG_AUTHPRIV``  | Private security / authorization messages             |
 796+-------------------+-------------------------------------------------------+
 797| ``LOG_CRON``      | Clock daemon (``cron`` and ``at``)                    |
 798+-------------------+-------------------------------------------------------+
 799| ``LOG_DAEMON``    | System daemon processes                               |
 800+-------------------+-------------------------------------------------------+
 801| ``LOG_KERN``      | Kernel messages                                       |
 802+-------------------+-------------------------------------------------------+
 803| ``LOG_LOCAL0`` .. | Reserved for local use; **not** available under       |
 804| ``LOG_LOCAL7``    | Windows.                                              |
 805+-------------------+-------------------------------------------------------+
 806| ``LOG_LPR``       | Printer subsystem                                     |
 807+-------------------+-------------------------------------------------------+
 808| ``LOG_MAIL``      | Mail subsystem                                        |
 809+-------------------+-------------------------------------------------------+
 810| ``LOG_NEWS``      | USENET news subsystem                                 |
 811+-------------------+-------------------------------------------------------+
 812| ``LOG_SYSLOG``    | Internal syslog messages                              |
 813+-------------------+-------------------------------------------------------+
 814| ``LOG_USER``      | Generic user-level messages                           |
 815+-------------------+-------------------------------------------------------+
 816| ``LOG_UUCP``      | UUCP subsystem                                        |
 817+-------------------+-------------------------------------------------------+
 818
 819.. _syslog(): http://www.php.net/syslog
 820.. _openlog(): http://www.php.net/openlog
 821
 822Example
 823~~~~~~~
 824::
 825
 826    $logger = &Log::singleton('syslog', LOG_LOCAL0, 'ident');
 827    for ($i = 0; $i < 10; $i++) {
 828        $logger->log("Log entry $i");
 829    }
 830
 831
 832The Window Handler
 833------------------
 834The Window handler sends log events to a separate browser window.  The
 835original idea for this handler was inspired by Craig Davis' Zend.com article
 836entitled `"JavaScript Power PHP Debugging"`_.
 837
 838Configuration
 839~~~~~~~~~~~~~
 840+-------------------+-----------+---------------+---------------------------+
 841| Parameter         | Type      | Default       | Description               |
 842+===================+===========+===============+===========================+
 843| ``title``         | String    | ``Log Output  | The title of the output   |
 844|                   |           | Window``      | window.                   |
 845+-------------------+-----------+---------------+---------------------------+
 846| ``styles``        | Array     | `ROY G BIV`_  | Mapping of log priorities |
 847|                   |           | (high to low) | to CSS styles.            |
 848+-------------------+-----------+---------------+---------------------------+
 849
 850.. _"JavaScript Power PHP Debugging": http://www.zend.com/zend/tut/tutorial-DebugLib.php
 851.. _ROY G BIV: http://www.cis.rit.edu/
 852
 853Example
 854~~~~~~~
 855::
 856
 857    $conf = array('title' => 'Sample Log Output');
 858    $logger = &Log::singleton('win', 'LogWindow', 'ident', $conf);
 859    for ($i = 0; $i < 10; $i++) {
 860        $logger->log("Log entry $i");
 861    }
 862
 863
 864Composite Handlers
 865==================
 866It is often useful to log events to multiple handlers.  The Log package
 867provides a compositing system that marks this task trivial.
 868
 869Start by creating the individual log handlers::
 870
 871    $console = &Log::singleton('console', '', 'TEST');
 872    $file = &Log::singleton('file', 'out.log', 'TEST');
 873
 874Then, construct a composite handler and add the individual handlers as
 875children of the composite::
 876
 877    $composite = &Log::singleton('composite');
 878    $composite->addChild($console);
 879    $composite->addChild($file);
 880
 881The composite handler implements the standard ``Log`` interface so you can use
 882it just like any of the other handlers::
 883
 884    $composite->log('This event will be logged to both handlers.');
 885
 886Children can be removed from the composite when they're not longer needed::
 887
 888    $composite->removeChild($file);
 889
 890
 891Log Observers
 892=============
 893Log observers provide an implementation of the `observer pattern`_.  In the
 894content of the Log package, they provide a mechanism by which you can examine
 895(i.e. observe) each event as it is logged.  This allows the implementation of
 896special behavior based on the contents of a log event.  For example, the
 897observer code could send an alert email if a log event contained the string
 898``PANIC``.
 899
 900Creating a log observer involves implementing a subclass of the
 901``Log_observer`` class.  The subclass must override the base class's
 902``notify()`` method.  This method is passed a hash containing the event's
 903priority and event.  The subclass's implementation is free to act upon this
 904information in any way it likes.
 905
 906Log observers are attached to ``Log`` instances via the ``attach()`` method::
 907
 908    $observer = &Log_observer::factory('yourType');
 909    $logger->attach($observer);
 910
 911Observers can be detached using the ``detach()`` method::
 912
 913    $logger->detach($observer);
 914
 915At this time, no concrete ``Log_observer`` implementations are distributed
 916with the Log package.
 917
 918.. _observer pattern: http://phppatterns.com/index.php/article/articleview/27/1/1/
 919
 920
 921Logging From Standard Error Handlers
 922====================================
 923
 924Logging PHP Errors
 925------------------
 926PHP's default error handler can be overridden using the `set_error_handler()`_
 927function.  The custom error handling function can use a global Log instance to
 928log the PHP errors.
 929
 930**Note:** Fatal PHP errors cannot be handled by a custom error handler at this
 931time.
 932
 933::
 934
 935    function errorHandler($code, $message, $file, $line)
 936    {
 937        global $logger;
 938
 939        /* Map the PHP error to a Log priority. */
 940        switch ($code) {
 941        case E_WARNING:
 942        case E_USER_WARNING:
 943            $priority = PEAR_LOG_WARNING;
 944            break;
 945        case E_NOTICE:
 946        case E_USER_NOTICE:
 947            $priority = PEAR_LOG_NOTICE;
 948            break;
 949        case E_ERROR:
 950        case E_USER_ERROR:
 951            $priority = PEAR_LOG_ERR;
 952            break;
 953        default:
 954            $priority = PEAR_LOG_INFO;
 955        }
 956
 957        $logger->log($message . ' in ' . $file . ' at line ' . $line,
 958                     $priority);
 959    }
 960
 961    set_error_handler('errorHandler');
 962    trigger_error('This is an information log message.', E_USER_NOTICE);
 963
 964.. _set_error_handler(): http://www.php.net/set_error_handler
 965
 966Logging PHP Assertions
 967----------------------
 968PHP allows user-defined `assert()`_ callback handlers.  The assertion callback
 969is configured using the `assert_options()`_ function.
 970
 971::
 972
 973    function assertCallback($file, $line, $message)
 974    {
 975        global $logger;
 976
 977        $logger->log($message . ' in ' . $file . ' at line ' . $line,
 978                     PEAR_LOG_ALERT);
 979    }
 980
 981    assert_options(ASSERT_CALLBACK, 'assertCallback');
 982    assert(false);
 983
 984.. _assert(): http://www.php.net/assert
 985.. _assert_options(): http://www.php.net/assert_options
 986
 987Logging PHP Exceptions
 988----------------------
 989PHP 5 and later support the concept of `exceptions`_.  A custom exception
 990handler can be assigned using the `set_exception_handler()`_ function.
 991
 992::
 993
 994    function exceptionHandler($exception)
 995    {
 996        global $logger;
 997
 998        $logger->log($exception->getMessage(), PEAR_LOG_ALERT);
 999    }
1000
1001    set_exception_handler('exceptionHandler');
1002    throw new Exception('Uncaught Exception');
1003
1004.. _exceptions: http://www.php.net/exceptions
1005.. _set_exception_handler(): http://www.php.net/set_exception_handler
1006
1007Logging PEAR Errors
1008-------------------
1009The Log package can be used with `PEAR::setErrorHandling()`_'s
1010``PEAR_ERROR_CALLBACK`` mechanism by writing an error handling function that
1011uses a global Log instance.  Here's an example::
1012
1013    function errorHandler($error)
1014    {
1015        global $logger;
1016
1017        $message = $error->getMessage();
1018
1019        if (!empty($error->backtrace[1]['file'])) {
1020            $message .= ' (' . $error->backtrace[1]['file'];
1021            if (!empty($error->backtrace[1]['line'])) {
1022                $message .= ' at line ' . $error->backtrace[1]['line'];
1023            }
1024            $message .= ')';
1025        }
1026
1027        $logger->log($message, $error->code);
1028    }
1029
1030    PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'errorHandler');
1031    PEAR::raiseError('This is an information log message.', PEAR_LOG_INFO);
1032
1033.. _PEAR::setErrorHandling(): http://pear.php.net/manual/en/core.pear.pear.seterrorhandling.php
1034
1035
1036Custom Handlers
1037===============
1038There are times when the standard handlers aren't a perfect match for your
1039needs.  In those situations, the solution might be to write a custom handler.
1040
1041Using a Custom Handler
1042----------------------
1043Using a custom Log handler is very simple.  Once written (see `Writing New
1044Handlers`_ and `Extending Existing Handlers`_ below), you have the choice of
1045placing the file in your PEAR installation's main ``Log/`` directory (usually
1046something like ``/usr/local/lib/php/Log`` or ``C:\php\pear\Log``), where it
1047can be found and use by any PHP application on the system, or placing the file
1048somewhere in your application's local hierarchy and including it before the
1049the custom Log object is constructed.
1050
1051Method 1: Handler in the Standard Location
1052~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1053After copying the handler file to your PEAR installation's ``Log/`` directory,
1054simply treat the handler as if it were part of the standard distributed.  If
1055your handler is named ``custom`` (and therefore implemented by a class named
1056``Log_custom``)::
1057
1058    require_once 'Log.php';
1059
1060    $logger = &Log::factory('custom', '', 'CUSTOM');
1061
1062
1063Method 2: Handler in a Custom Location
1064~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1065If you prefer storing your handler in your application's local hierarchy,
1066you'll need to include that file before you can create a Log instance based on
1067it.
1068
1069::
1070
1071    require_once 'Log.php';
1072    require_once 'LocalHandlers/custom.php';
1073
1074    $logger = &Log::factory('custom', '', 'CUSTOM');
1075
1076
1077Writing New Handlers
1078--------------------
1079
1080TODO
1081
1082Extending Existing Handlers
1083---------------------------
1084
1085TODO
1086
1087
1088.. |required| replace:: **[required]**
1089
1090.. vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab textwidth=78 ft=rst: