home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2005 June / PCpro_2005_06.ISO / files / opensource / xamp / xampp-win32.exe / xampp / guide.txt < prev    next >
Encoding:
Text File  |  2004-10-01  |  36.2 KB  |  895 lines

  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: 2004/08/19 06:35:57 $
  12. :Revision:      $Revision: 1.13 $
  13.  
  14. .. contents:: Contents
  15. .. section-numbering::
  16.  
  17. Using Log Handlers
  18. ==================
  19.  
  20. The Log package is implemented as a framework that supports the notion of
  21. backend-specific log handlers.  The base logging object (defined by the `Log
  22. class`_) is primarily an abstract interface to the currently configured
  23. handler.
  24.  
  25. A wide variety of handlers are distributed with the Log package, and, should
  26. none 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.  
  31. Creating a Log Object
  32. ---------------------
  33. There are three ways to create Log objects:
  34.  
  35.     - Using the ``Log::factory()`` method
  36.     - Using the ``Log::singleton()`` method
  37.     - Direct instantiation
  38.  
  39. The Factory Method
  40. ~~~~~~~~~~~~~~~~~~
  41. The ``Log::factory()`` method implements the `Factory Pattern`_.  It allows
  42. for the parameterized construction of concrete Log instances at runtime.  The
  43. first parameter to the ``Log::factory()`` method indicates the name of the
  44. concrete handler to create.  The rest of the parameters will be passed on to
  45. the handler's constructor (see `Configuring a Handler`_ below).
  46.  
  47. The 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.  
  61. The Singleton Method
  62. ~~~~~~~~~~~~~~~~~~~~
  63. The ``Log::singleton()`` method implements the `Singleton Pattern`_.  The
  64. singleton pattern ensures that only a single instance of a given log type and
  65. configuration is ever created.  This has two benefits: first, it prevents
  66. duplicate ``Log`` instances from being constructed, and, second, it gives all
  67. of your code access to the same ``Log`` instance.  The latter is especially
  68. important when logging to files because only a single file handler will need
  69. to be managed.
  70.  
  71. The ``Log::singleton()`` method's parameters match the ``Log::factory()``
  72. method.  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.  
  96. Direct Instantiation
  97. ~~~~~~~~~~~~~~~~~~~~
  98. It is also possible to directly instantiate concrete ``Log`` handler
  99. instances.  However, this method is **not recommended** because it creates a
  100. tighter coupling between your application code and the Log package than is
  101. necessary.  Use of `the factory method`_ or `the singleton method`_ is
  102. preferred.
  103.  
  104.  
  105. Configuring a Handler
  106. ---------------------
  107. A log handler's configuration is determined by the arguments used in its
  108. construction.  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.  
  146. Logging an Event
  147. ----------------
  148. Events are logged using the ``log()`` method::
  149.  
  150.     $logger->log('Message', PEAR_LOG_NOTICE);
  151.  
  152. The first argument contains the log event's message.  Even though the event is
  153. always logged as a string, it is possible to pass an object to the ``log()``
  154. method.  If the object implements a ``getString()`` method, a ``toString()``
  155. method or Zend Engine 2's special ``__toString()`` casting method, it will be
  156. used to determine the object's string representation.  Otherwise, the
  157. `serialized`_ form of the object will be logged.
  158.  
  159. The second, optional argument specifies the log event's priority.  See the
  160. `Log Levels`_ table for the complete list of priorities.  The default priority
  161. is PEAR_LOG_INFO.
  162.  
  163. The ``log()`` method will return ``true`` if the event was successfully
  164. logged.
  165.  
  166. "Shortcut" methods are also available for logging an event at a specific log
  167. level.  See the `Log Levels`_ table for the complete list.
  168.  
  169. .. _serialized: http://www.php.net/serialize
  170.  
  171.  
  172. Log Levels
  173. ----------
  174. This table is ordered by highest priority (``PEAR_LOG_EMERG``) to lowest
  175. priority (``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.  
  198. Log Level Masks
  199. ---------------
  200. Defining a log level mask allows you to include and/or exclude specific levels
  201. of events from being logged.  The ``$level`` construction parameter (see
  202. `Configuring a Handler`_) uses this mechanism to exclude log events below a
  203. certain priority, and it's possible to define more complex masks once the Log
  204. object has been constructed.
  205.  
  206. Each priority has a specific mask associated with it.  To compute a priority's
  207. mask, use the static ``Log::MASK()`` method::
  208.  
  209.     $mask = Log::MASK(PEAR_LOG_INFO);
  210.  
  211. To compute the mask for all priorities up to a certain level, use the
  212. ``Log::UPTO()`` method::
  213.  
  214.     $mask = Log::UPTO(PEAR_LOG_INFO);
  215.  
  216. The apply the mask, use the ``setMask()`` method::
  217.  
  218.     $logger->setMask($mask);
  219.  
  220. Masks can be be combined using bitwise operations.  To restrict logging to
  221. only those events marked as ``PEAR_LOG_NOTICE`` or ``PEAR_LOG_DEBUG``::
  222.  
  223.     $mask = Log::MASK(PEAR_LOG_NOTICE) | Log::MASK(PEAR_LOG_DEBUG);
  224.     $logger->setMask($mask);
  225.  
  226. For convenience, two special masks are predefined: ``PEAR_LOG_NONE`` and
  227. ``PEAR_LOG_ALL``.  ``PEAR_LOG_ALL`` is especially useful for exluding only
  228. specific priorities::
  229.  
  230.     $mask = PEAR_LOG_ALL ^ Log::MASK(PEAR_LOG_NOTICE);
  231.     $logger->setMask($mask);
  232.  
  233. It is also possible to retrieve and modify a Log object's existing mask::
  234.  
  235.     $mask = $logger->getMask() | Log::MASK(PEAR_LOG_INFO);
  236.     $logger->setMask($mask);
  237.  
  238.  
  239. Flushing Log Events
  240. -------------------
  241. Some log handlers (such as `the console handler`_) support explicit
  242. "buffering".  When buffering is enabled, log events won't actually be written
  243. to the output stream until the handler is closed.  Other handlers (such as
  244. `the file handler`_) support implicit buffering because they use the operating
  245. system's IO routines, which may buffer the output.
  246.  
  247. It's possible to force these handlers to flush their output, however, by
  248. calling their ``flush()`` method::
  249.  
  250.     $conf = array('buffering' => true);
  251.     $logger = &Log::singleton('console', '', 'test', $conf);
  252.  
  253.     for ($i = 0; $i < 10; $i++) {
  254.         $logger->log('This event will be buffered.');
  255.     }
  256.  
  257.     /* Flush all of the buffered log events. */
  258.     $logger->flush();
  259.  
  260.     for ($i = 0; $i < 10; $i++) {
  261.         $logger->log('This event will be buffered.');
  262.     }
  263.  
  264.     /* Implicitly flush the buffered events on close. */
  265.     $logger->close();
  266.  
  267. At this time, the ``flush()`` method is only implemented by `the console
  268. handler`_, `the file handler`_ and `the mail handler`_.
  269.  
  270.  
  271. Standard Log Handlers
  272. =====================
  273.  
  274. The Console Handler
  275. -------------------
  276. The Console handler outputs log events directly to the console.  It supports
  277. output buffering and configurable string formats.
  278.  
  279. Configuration
  280. ~~~~~~~~~~~~~
  281. +-------------------+-----------+---------------+---------------------------+
  282. | Parameter         | Type      | Default       | Description               |
  283. +===================+===========+===============+===========================+
  284. | ``stream``        | File      | STDOUT_       | The output stream to use. |
  285. +-------------------+-----------+---------------+---------------------------+
  286. | ``buffering``     | Boolean   | False         | Should the output be      |
  287. |                   |           |               | buffered until shutdown?  |
  288. +-------------------+-----------+---------------+---------------------------+
  289. | ``lineFormat``    | String    | ``%1$s %2$s   | Log line format           |
  290. |                   |           | [%3$s] %4$s`` | specification.            |
  291. +-------------------+-----------+---------------+---------------------------+
  292. | ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
  293. |                   |           | %H:%M:%S``    | (for strftime_).          |
  294. +-------------------+-----------+---------------+---------------------------+
  295.  
  296. .. _STDOUT: http://www.php.net/wrappers.php
  297. .. _strftime: http://www.php.net/strftime
  298.  
  299. Example
  300. ~~~~~~~
  301. ::
  302.  
  303.     $logger = &Log::singleton('console', '', 'ident');
  304.     for ($i = 0; $i < 10; $i++) {
  305.         $logger->log("Log entry $i");
  306.     }
  307.  
  308.  
  309. The Display Handler
  310. -------------------
  311. The Display handler simply prints the log events back to the browser.  It
  312. respects the ``error_prepend_string`` and ``error_append_string`` `error
  313. handling values`_ and is useful when `logging from standard error handlers`_.
  314.  
  315. Configuration
  316. ~~~~~~~~~~~~~
  317. +-------------------+-----------+---------------+---------------------------+
  318. | Parameter         | Type      | Default       | Description               |
  319. +===================+===========+===============+===========================+
  320. | ``error_prepend`` | String    | PHP INI value | This string will be       |
  321. |                   |           |               | prepended to the log      |
  322. |                   |           |               | output.                   |
  323. +-------------------+-----------+---------------+---------------------------+
  324. | ``error_append``  | String    | PHP INI value | This string will be       |
  325. |                   |           |               | appended to the log       |
  326. |                   |           |               | output.                   |
  327. +-------------------+-----------+---------------+---------------------------+
  328.  
  329. .. _error handling values: http://www.php.net/errorfunc
  330.  
  331. Example
  332. ~~~~~~~
  333. ::
  334.  
  335.     $conf = array('error_prepend' => '<font color="#ff0000"><tt>',
  336.                   'error_append'  => '</tt></font>');
  337.     $logger = &Log::singleton('display', '', '', $conf, PEAR_LOG_DEBUG);
  338.     for ($i = 0; $i < 10; $i++) {
  339.         $logger->log("Log entry $i");
  340.     }
  341.  
  342.  
  343. The Error_Log Handler
  344. ---------------------
  345. The Error_Log handler sends log events to PHP's `error_log()`_ function.
  346.  
  347. Configuration
  348. ~~~~~~~~~~~~~
  349. +-------------------+-----------+---------------+---------------------------+
  350. | Parameter         | Type      | Default       | Description               |
  351. +===================+===========+===============+===========================+
  352. | ``destination``   | String    | '' `(empty)`  | Optional destination value|
  353. |                   |           |               | for `error_log()`_.  See  |
  354. |                   |           |               | `Error_Log Types`_ for    |
  355. |                   |           |               | more details.             |
  356. +-------------------+-----------+---------------+---------------------------+
  357. | ``extra_headers`` | String    | '' `(empty)`  | Additional headers to pass|
  358. |                   |           |               | to the `mail()`_ function |
  359. |                   |           |               | when the                  |
  360. |                   |           |               | ``PEAR_LOG_TYPE_MAIL``    |
  361. |                   |           |               | type is specified.        |
  362. +-------------------+-----------+---------------+---------------------------+
  363.  
  364. Error_Log Types
  365. ~~~~~~~~~~~~~~~
  366. All of the available log types are detailed in the `error_log()`_ section of
  367. the PHP manual.  For your convenience, the Log package also defines the
  368. following constants that can be used for the ``$name`` handler construction
  369. parameter.
  370.  
  371. +---------------------------+-----------------------------------------------+
  372. | Constant                  | Description                                   |
  373. +===========================+===============================================+
  374. | ``PEAR_LOG_TYPE_SYSTEM``  | Log events are sent to PHP's system logger,   |
  375. |                           | which uses the operating system's logging     |
  376. |                           | mechanism or a file (depending on the value   |
  377. |                           | of the `error_log configuration directive`_). |
  378. +---------------------------+-----------------------------------------------+
  379. | ``PEAR_LOG_TYPE_MAIL``    | Log events are sent via email to the address  |
  380. |                           | specified in the ``destination`` value.       |
  381. +---------------------------+-----------------------------------------------+
  382. | ``PEAR_LOG_TYPE_DEBUG``   | Log events are sent through PHP's debugging   |
  383. |                           | connection.  This will only work if           |
  384. |                           | `remote debugging`_ has been enabled.  The    |
  385. |                           | ``destination`` value is used to specify the  |
  386. |                           | host name or IP address of the target socket. |
  387. +---------------------------+-----------------------------------------------+
  388. | ``PEAR_LOG_TYPE_FILE``    | Log events will be appended to the file named |
  389. |                           | by the ``destination`` value.                 |
  390. +---------------------------+-----------------------------------------------+
  391.  
  392. .. _error_log(): http://www.php.net/error_log
  393. .. _mail(): http://www.php.net/mail
  394. .. _error_log configuration directive: http://www.php.net/errorfunc#ini.error-log
  395. .. _remote debugging: http://www.php.net/install.configure#install.configure.enable-debugger
  396.  
  397. Example
  398. ~~~~~~~
  399. ::
  400.  
  401.     $logger = &Log::singleton('error_log', PEAR_LOG_TYPE_SYSTEM, 'ident');
  402.     for ($i = 0; $i < 10; $i++) {
  403.         $logger->log("Log entry $i");
  404.     }
  405.  
  406.  
  407. The File Handler
  408. ----------------
  409. The File handler writes log events to a text file using configurable string
  410. formats.
  411.  
  412. Configuration
  413. ~~~~~~~~~~~~~
  414. +-------------------+-----------+---------------+---------------------------+
  415. | Parameter         | Type      | Default       | Description               |
  416. +===================+===========+===============+===========================+
  417. | ``append``        | Boolean   | True          | Should new log entries be |
  418. |                   |           |               | append to an existing log |
  419. |                   |           |               | file, or should the a new |
  420. |                   |           |               | log file overwrite an     |
  421. |                   |           |               | existing one?             |
  422. +-------------------+-----------+---------------+---------------------------+
  423. | ``mode``          | Integer   | 0644          | Octal representation of   |
  424. |                   |           |               | the log file's permissions|
  425. |                   |           |               | mode.                     |
  426. +-------------------+-----------+---------------+---------------------------+
  427. | ``eol``           | String    | OS default    | The end-on-line character |
  428. |                   |           |               | sequence.                 |
  429. +-------------------+-----------+---------------+---------------------------+
  430. | ``lineFormat``    | String    | ``%1$s %2$s   | Log line format           |
  431. |                   |           | [%3$s] %4$s`` | specification.            |
  432. +-------------------+-----------+---------------+---------------------------+
  433. | ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
  434. |                   |           | %H:%M:%S``    | (for strftime_).          |
  435. +-------------------+-----------+---------------+---------------------------+
  436.  
  437. .. _strftime: http://www.php.net/strftime
  438.  
  439. Example
  440. ~~~~~~~
  441. ::
  442.  
  443.     $conf = array('mode' => 0600, 'timeFormat' => '%X %x');
  444.     $logger = &Log::singleton('file', 'out.log', 'ident', $conf);
  445.     for ($i = 0; $i < 10; $i++) {
  446.         $logger->log("Log entry $i");
  447.     }
  448.  
  449.  
  450. The Mail Handler
  451. ----------------
  452. The Mail handler aggregates a session's log events and sends them in the body
  453. of an email message using PHP's `mail()`_ function.
  454.  
  455. Configuration
  456. ~~~~~~~~~~~~~
  457. +-------------------+-----------+---------------+---------------------------+
  458. | Parameter         | Type      | Default       | Description               |
  459. +===================+===========+===============+===========================+
  460. | ``from``          | String    | sendmail_from | Value for the message's   |
  461. |                   |           | INI value     | ``From:`` header.         |
  462. +-------------------+-----------+---------------+---------------------------+
  463. | ``subject``       | String    | ``[Log_mail]  | Value for the message's   |
  464. |                   |           | Log message`` | ``Subject:`` header.      |
  465. +-------------------+-----------+---------------+---------------------------+
  466. | ``preamble``      | String    | `` `(empty)`  | Preamble for the message. |
  467. +-------------------+-----------+---------------+---------------------------+
  468.  
  469. .. _mail(): http://www.php.net/mail
  470.  
  471. Example
  472. ~~~~~~~
  473. ::
  474.  
  475.     $conf = array('subject' => 'Important Log Events');
  476.     $logger = &Log::singleton('mail', 'webmaster@example.com', 'ident', $conf);
  477.     for ($i = 0; $i < 10; $i++) {
  478.         $logger->log("Log entry $i");
  479.     }
  480.  
  481.  
  482. The Null Handler
  483. ----------------
  484. The Null handler simply consumes log events (akin to sending them to
  485. ``/dev/null``).  `Log level masks`_ are respected, and the event will still be
  486. sent to any registered `log observers`_.
  487.  
  488. Example
  489. ~~~~~~~
  490. ::
  491.  
  492.     $logger = &Log::singleton('null');
  493.     for ($i = 0; $i < 10; $i++) {
  494.         $logger->log("Log entry $i");
  495.     }
  496.  
  497.  
  498. The SQL (DB) Handler
  499. --------------------
  500.  
  501. The SQL handler sends log events to a database using `PEAR's DB abstraction
  502. layer`_.
  503.  
  504. **Note:** Due to the constraints of the database schema, the SQL handler
  505. limits the length of the ``$ident`` string to sixteen (16) characters.
  506.  
  507. Configuration
  508. ~~~~~~~~~~~~~
  509. +-------------------+-----------+---------------+---------------------------+
  510. | Parameter         | Type      | Default       | Description               |
  511. +===================+===========+===============+===========================+
  512. | ``dsn``           | String    | '' `(empty)`  | A `Data Source Name`_.    |
  513. |                   |           |               | |required|                |
  514. +-------------------+-----------+---------------+---------------------------+
  515. | ``db``            | Object    | NULL          | An existing `DB`_ object. |
  516. |                   |           |               | If specified, this object |
  517. |                   |           |               | will be used, and ``dsn`` |
  518. |                   |           |               | will be ignored.          |
  519. +-------------------+-----------+---------------+---------------------------+
  520. | ``sequence``      | String    | ``log_id``    | The name of the sequence  |
  521. |                   |           |               | to use when generating    |
  522. |                   |           |               | unique event IDs.         |
  523. +-------------------+-----------+---------------+---------------------------+
  524. | ``identLimit``    | Integer   | 16            | The maximum length of the |
  525. |                   |           |               | ``ident`` string.         |
  526. |                   |           |               | **Changing this value may |
  527. |                   |           |               | require updates to the SQL|
  528. |                   |           |               | schema, as well.**        |
  529. +-------------------+-----------+---------------+---------------------------+
  530.  
  531. .. _DB: http://pear.php.net/package/DB
  532. .. _PEAR's DB abstraction layer: DB_
  533. .. _Data Source Name: http://pear.php.net/manual/en/package.database.db.intro-dsn.php
  534.  
  535. Examples
  536. ~~~~~~~~
  537. Using a `Data Source Name`_ to create a new database connection::
  538.  
  539.     $conf = array('dsn' => 'pgsql://jon@localhost+unix/logs');
  540.     $logger = &Log::singleton('sql', 'log_table', 'ident', $conf);
  541.     for ($i = 0; $i < 10; $i++) {
  542.         $logger->log("Log entry $i");
  543.     }
  544.  
  545. Using an existing `DB`_ object::
  546.  
  547.     require_once 'DB.php';
  548.     $db = &DB::connect('pgsql://jon@localhost+unix/logs');
  549.  
  550.     $conf['db'] = $db;
  551.     $logger = &Log::singleton('sql', 'log_table', 'ident', $conf);
  552.     for ($i = 0; $i < 10; $i++) {
  553.         $logger->log("Log entry $i");
  554.     }
  555.  
  556.  
  557. The Sqlite Handler
  558. ------------------
  559. :Author:        Bertrand Mansion
  560. :Contact:       bmansion@mamasam.com
  561.  
  562. The Sqlite handler sends log events to an Sqlite database using the `native
  563. PHP sqlite functions`_.
  564.  
  565. It is faster than `the SQL (DB) handler`_ because requests are made directly
  566. to the database without using an abstraction layer.  It is also interesting to
  567. note that Sqlite database files can be moved, copied, and deleted on your
  568. system just like any other files, which makes log management easier.  Last but
  569. not least, using a database to log your events allows you to use SQL queries
  570. to create reports and statistics.
  571.  
  572. When using a database and logging a lot of events, it is recommended to split
  573. the database into smaller databases.  This is allowed by Sqlite, and you can
  574. later use the Sqlite `ATTACH`_ statement to query your log database files
  575. globally.
  576.  
  577. If the database does not exist when the log is opened, sqlite will try to
  578. create it automatically. If the log table does not exist, it will also be
  579. automatically created.  The table creation uses the following SQL request::
  580.  
  581.     CREATE TABLE log_table (
  582.         id          INTEGER PRIMARY KEY NOT NULL,
  583.         logtime     NOT NULL,
  584.         ident       CHAR(16) NOT NULL,
  585.         priority    INT NOT NULL,
  586.         message
  587.     );
  588.  
  589. Configuration
  590. ~~~~~~~~~~~~~
  591. +-------------------+-----------+---------------+---------------------------+
  592. | Parameter         | Type      | Default       | Description               |
  593. +===================+===========+===============+===========================+
  594. | ``filename``      | String    | '' `(empty)`  | Path to an Sqlite         |
  595. |                   |           |               | database. |required|      |
  596. +-------------------+-----------+---------------+---------------------------+
  597. | ``mode``          | Integer   | 0666          | Octal mode used to open   |
  598. |                   |           |               | the database.             |
  599. +-------------------+-----------+---------------+---------------------------+
  600. | ``persistent``    | Boolean   | false         | Use a persistent          |
  601. |                   |           |               | connection.               |
  602. +-------------------+-----------+---------------+---------------------------+
  603.  
  604. An already opened database connection can also be passed as parameter instead
  605. of the above configuration.  In this case, closing the database connection is
  606. up to the user.
  607.  
  608. .. _native PHP sqlite functions: http://www.php.net/sqlite
  609. .. _ATTACH: http://www.sqlite.org/lang.html#attach
  610.  
  611. Examples
  612. ~~~~~~~~
  613. Using a configuration to create a new database connection::
  614.  
  615.     $conf = array('filename' => 'log.db', 'mode' => 0666, 'persistent' => true);
  616.     $logger =& Log::factory('sqlite', 'log_table', 'ident', $conf);
  617.     $logger->log('logging an event', PEAR_LOG_WARNING);
  618.  
  619. Using an existing connection::
  620.  
  621.     $db = sqlite_open('log.db', 0666, $error);
  622.     $logger =& Log::factory('sqlite', 'log_table', 'ident', $db);
  623.     $logger->log('logging an event', PEAR_LOG_WARNING);
  624.     sqlite_close($db);
  625.  
  626.  
  627. The Syslog Handler
  628. ------------------
  629. The Syslog handler sends log events to the system logging service (syslog on
  630. Unix-like environments or the Event Log on Windows systems).  The events are
  631. sent using PHP's `syslog()`_ function.
  632.  
  633. Facilities
  634. ~~~~~~~~~~
  635. +-------------------+-------------------------------------------------------+
  636. | Constant          | Category Description                                  |
  637. +===================+=======================================================+
  638. | ``LOG_AUTH``      | Security / authorization messages; ``LOG_AUTHPRIV`` is|
  639. |                   | preferred on systems where it is defined.             |
  640. +-------------------+-------------------------------------------------------+
  641. | ``LOG_AUTHPRIV``  | Private security / authorization messages             |
  642. +-------------------+-------------------------------------------------------+
  643. | ``LOG_CRON``      | Clock daemon (``cron`` and ``at``)                    |
  644. +-------------------+-------------------------------------------------------+
  645. | ``LOG_DAEMON``    | System daemon processes                               |
  646. +-------------------+-------------------------------------------------------+
  647. | ``LOG_KERN``      | Kernel messages                                       |
  648. +-------------------+-------------------------------------------------------+
  649. | ``LOG_LOCAL0`` .. | Reserved for local use; **not** available under       |
  650. | ``LOG_LOCAL7``    | Windows.                                              |
  651. +-------------------+-------------------------------------------------------+
  652. | ``LOG_LPR``       | Printer subsystem                                     |
  653. +-------------------+-------------------------------------------------------+
  654. | ``LOG_MAIL``      | Mail subsystem                                        |
  655. +-------------------+-------------------------------------------------------+
  656. | ``LOG_NEWS``      | USENET news subsystem                                 |
  657. +-------------------+-------------------------------------------------------+
  658. | ``LOG_SYSLOG``    | Internal syslog messages                              |
  659. +-------------------+-------------------------------------------------------+
  660. | ``LOG_USER``      | Generic user-level messages                           |
  661. +-------------------+-------------------------------------------------------+
  662. | ``LOG_UUCP``      | UUCP subsystem                                        |
  663. +-------------------+-------------------------------------------------------+
  664.  
  665. .. _syslog(): http://www.php.net/syslog
  666.  
  667. Example
  668. ~~~~~~~
  669. ::
  670.  
  671.     $logger = &Log::singleton('syslog', LOG_LOCAL0, 'ident');
  672.     for ($i = 0; $i < 10; $i++) {
  673.         $logger->log("Log entry $i");
  674.     }
  675.  
  676.  
  677. The Window Handler
  678. ------------------
  679. The Window handler sends log events to a separate browser window.  The
  680. original idea for this handler was inspired by Craig Davis' Zend.com article
  681. entitled `"JavaScript Power PHP Debugging"`_.
  682.  
  683. Configuration
  684. ~~~~~~~~~~~~~
  685. +-------------------+-----------+---------------+---------------------------+
  686. | Parameter         | Type      | Default       | Description               |
  687. +===================+===========+===============+===========================+
  688. | ``title``         | String    | ``Log Output  | The title of the output   |
  689. |                   |           | Window``      | window.                   |
  690. +-------------------+-----------+---------------+---------------------------+
  691. | ``colors``        | Array     | `ROY G BIV`_  | Mapping of log priorities |
  692. |                   |           | (high to low) | to colors.                |
  693. +-------------------+-----------+---------------+---------------------------+
  694.  
  695. .. _"JavaScript Power PHP Debugging": http://www.zend.com/zend/tut/tutorial-DebugLib.php
  696. .. _ROY G BIV: http://www.cis.rit.edu/
  697.  
  698. Example
  699. ~~~~~~~
  700. ::
  701.  
  702.     $conf = array('title' => 'Sample Log Output');
  703.     $logger = &Log::singleton('win', 'LogWindow', 'ident', $conf);
  704.     for ($i = 0; $i < 10; $i++) {
  705.         $logger->log("Log entry $i");
  706.     }
  707.  
  708.  
  709. Composite Handlers
  710. ==================
  711. It is often useful to log events to multiple handlers.  The Log package
  712. provides a compositing system that marks this task trivial.
  713.  
  714. Start by creating the individual log handlers::
  715.  
  716.     $console = &Log::singleton('console', '', 'TEST');
  717.     $file = &Log::singleton('file', 'out.log', 'TEST');
  718.  
  719. Then, construct a composite handler and add the individual handlers as
  720. children of the composite::
  721.  
  722.     $composite = &Log::singleton('composite');
  723.     $composite->addChild($console);
  724.     $composite->addChild($file);
  725.  
  726. The composite handler implements the standard ``Log`` interface so you can use
  727. it just like any of the other handlers::
  728.  
  729.     $composite->log('This event will be logged to both handlers.');
  730.  
  731. Children can be removed from the composite when they're not longer needed::
  732.  
  733.     $composite->removeChild($file);
  734.  
  735.  
  736. Log Observers
  737. =============
  738. Log observers provide an implementation of the `observer pattern`_.  In the
  739. content of the Log package, they provide a mechanism by which you can examine
  740. (i.e. observe) each event as it is logged.  This allows the implementation of
  741. special behavior based on the contents of a log event.  For example, the
  742. observer code could send an alert email if a log event contained the string
  743. ``PANIC``.
  744.  
  745. Creating a log observer involves implementing a subclass of the
  746. ``Log_observer`` class.  The subclass must override the base class's
  747. ``notify()`` method.  This method is passed a hash containing the event's
  748. priority and event.  The subclass's implementation is free to act upon this
  749. information in any way it likes.
  750.  
  751. Log observers are attached to ``Log`` instances via the ``attach()`` method::
  752.  
  753.     $observer = &Log_observer::factory('yourType');
  754.     $logger->attach($observer);
  755.  
  756. Observers can be detached using the ``detach()`` method::
  757.  
  758.     $logger->detach($observer);
  759.  
  760. At this time, no concrete ``Log_observer`` implementations are distributed
  761. with the Log package.
  762.  
  763. .. _observer pattern: http://phppatterns.com/index.php/article/articleview/27/1/1/
  764.  
  765.  
  766. Logging From Standard Error Handlers
  767. ====================================
  768.  
  769. Logging PHP Errors
  770. ------------------
  771. PHP's default error handler can be overridden using the `set_error_handler()`_
  772. function.  The custom error handling function can use a global Log instance to
  773. log the PHP errors.
  774.  
  775. **Note:** Fatal PHP errors cannot be handled by a custom error handler at this
  776. time.
  777.  
  778. ::
  779.  
  780.     function errorHandler($code, $message, $file, $line)
  781.     {
  782.         global $logger;
  783.  
  784.         /* Map the PHP error to a Log priority. */
  785.         switch ($code) {
  786.         case E_WARNING:
  787.         case E_USER_WARNING:
  788.             $priority = PEAR_LOG_WARNING;
  789.             break;
  790.         case E_NOTICE:
  791.         case E_USER_NOTICE:
  792.             $priority = PEAR_LOG_NOTICE;
  793.             break;
  794.         case E_ERROR:
  795.         case E_USER_ERROR:
  796.             $priority = PEAR_LOG_ERR;
  797.             break;
  798.         default:
  799.             $priotity = PEAR_LOG_INFO;
  800.         }
  801.  
  802.         $logger->log($message . ' in ' . $file . ' at line ' . $line,
  803.                      $priority);
  804.     }
  805.  
  806.     set_error_handler('errorHandler');
  807.     trigger_error('This is an information log message.', E_USER_NOTICE);
  808.  
  809. .. _set_error_handler(): http://www.php.net/set_error_handler
  810.  
  811. Logging PEAR Errors
  812. -------------------
  813. The Log package can be used with `PEAR::setErrorHandling()`_'s
  814. ``PEAR_ERROR_CALLBACK`` mechanism by writing an error handling function that
  815. uses a global Log instance.  Here's an example::
  816.  
  817.     function errorHandler($error)
  818.     {
  819.         global $logger;
  820.  
  821.         $message = $error->getMessage();
  822.  
  823.         if (!empty($error->backtrace[1]['file'])) {
  824.             $message .= ' (' . $error->backtrace[1]['file'];
  825.             if (!empty($error->backtrace[1]['line'])) {
  826.                 $message .= ' at line ' . $error->backtrace[1]['line'];
  827.             }
  828.             $message .= ')';
  829.         }
  830.  
  831.         $logger->log($message, $error->code);
  832.     }
  833.  
  834.     PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'errorHandler');
  835.     PEAR::raiseError('This is an information log message.', PEAR_LOG_INFO);
  836.  
  837. .. _PEAR::setErrorHandling(): http://pear.php.net/manual/en/core.pear.pear.seterrorhandling.php
  838.  
  839.  
  840. Custom Handlers
  841. ===============
  842. There are times when the standard handlers aren't a perfect match for your
  843. needs.  In those situations, the solution might be to write a custom handler.
  844.  
  845. Using a Custom Handler
  846. ----------------------
  847. Using a custom Log handler is very simple.  Once written (see `Writing New
  848. Handlers`_ and `Extending Existing Handlers`_ below), you have the choice of
  849. placing the file in your PEAR installation's main ``Log/`` directory (usually
  850. something like ``/usr/local/lib/php/Log`` or ``C:\php\pear\Log``), where it
  851. can be found and use by any PHP application on the system, or placing the file
  852. somewhere in your application's local hierarchy and including it before the
  853. the custom Log object is constructed.
  854.  
  855. Method 1: Handler in the Standard Location
  856. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  857. After copying the handler file to your PEAR installation's ``Log/`` directory,
  858. simply treat the handler as if it were part of the standard distributed.  If
  859. your handler is named ``custom`` (and therefore implemented by a class named
  860. ``Log_custom``)::
  861.  
  862.     require_once 'Log.php';
  863.  
  864.     $logger = &Log::factory('custom', '', 'CUSTOM');
  865.  
  866.  
  867. Method 2: Handler in a Custom Location
  868. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  869. If you prefer storing your handler in your application's local hierarchy,
  870. you'll need to include that file before you can create a Log instance based on
  871. it.
  872.  
  873. ::
  874.  
  875.     require_once 'Log.php';
  876.     require_once 'LocalHandlers/custom.php';
  877.  
  878.     $logger = &Log::factory('custom', '', 'CUSTOM');
  879.  
  880.  
  881. Writing New Handlers
  882. --------------------
  883.  
  884. TODO
  885.  
  886. Extending Existing Handlers
  887. ---------------------------
  888.  
  889. TODO
  890.  
  891.  
  892. .. |required| replace:: **[required]**
  893.  
  894. .. vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab textwidth=78 ft=rst:
  895.