Subversion-Projekte lars-tiefland.php_share

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 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: 2011-02-15 21:13:19 -0800 (Tue, 15 Feb 2011) $
12
:Revision:      $Revision: 308379 $
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/viewvc.cgi/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://wikipedia.org/wiki/Factory_method_pattern
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://wikipedia.org/wiki/Singleton_pattern
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, and including, a certain level,
212
use the ``Log::MAX()`` static method::
213
 
214
    $mask = Log::MAX(PEAR_LOG_INFO);
215
 
216
To compute the mask for all priorities greater than or equal to a certain
217
level, use the ``Log::MIN()`` static method::
218
 
219
    $mask = Log::MIN(PEAR_LOG_INFO);
220
 
221
The apply the mask, use the ``setMask()`` method::
222
 
223
    $logger->setMask($mask);
224
 
225
Masks can be be combined using bitwise operations.  To restrict logging to
226
only 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
 
231
For convenience, two special masks are predefined: ``PEAR_LOG_NONE`` and
232
``PEAR_LOG_ALL``.  ``PEAR_LOG_ALL`` is especially useful for excluding only
233
specific priorities::
234
 
235
    $mask = PEAR_LOG_ALL ^ Log::MASK(PEAR_LOG_NOTICE);
236
    $logger->setMask($mask);
237
 
238
It 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
 
244
Log Line Format
245
---------------
246
Most log handlers support configurable line formats.  The following is a list
247
of special tokens that will be expanded at runtime with contextual information
248
related to the log event.  Each token has an alternate shorthand notation, as
249
well.
250
 
251
+------------------+-----------+--------------------------------------------+
252
| Token            | Alternate | Description                                |
253
+==================+===========+============================================+
254
| ``%{timestamp}`` | ``%1$s``  | Timestamp.  This is often configurable.    |
255
+------------------+-----------+--------------------------------------------+
256
| ``%{ident}``     | ``%2$s``  | The log handler's identification string.   |
257
+------------------+-----------+--------------------------------------------+
258
| ``%{priority}``  | ``%3$s``  | The log event's priority.                  |
259
+------------------+-----------+--------------------------------------------+
260
| ``%{message}``   | ``%4$s``  | The log event's message text.              |
261
+------------------+-----------+--------------------------------------------+
262
| ``%{file}``      | ``%5$s``  | The full filename of the logging file.     |
263
+------------------+-----------+--------------------------------------------+
264
| ``%{line}``      | ``%6$s``  | The line number on which the event occured.|
265
+------------------+-----------+--------------------------------------------+
266
| ``%{function}``  | ``%7$s``  | The function from which the event occurred.|
267
+------------------+-----------+--------------------------------------------+
268
| ``%{class}``     | ``%8$s``  | The class in which the event occurred.     |
269
+------------------+-----------+--------------------------------------------+
270
 
271
 
272
Flushing Log Events
273
-------------------
274
Some log handlers (such as `the console handler`_) support explicit
275
"buffering".  When buffering is enabled, log events won't actually be written
276
to the output stream until the handler is closed.  Other handlers (such as
277
`the file handler`_) support implicit buffering because they use the operating
278
system's IO routines, which may buffer the output.
279
 
280
It's possible to force these handlers to flush their output, however, by
281
calling their ``flush()`` method::
282
 
283
    $conf = array('buffering' => true);
284
    $logger = Log::singleton('console', '', 'test', $conf);
285
 
286
    for ($i = 0; $i < 10; $i++) {
287
        $logger->log('This event will be buffered.');
288
    }
289
 
290
    /* Flush all of the buffered log events. */
291
    $logger->flush();
292
 
293
    for ($i = 0; $i < 10; $i++) {
294
        $logger->log('This event will be buffered.');
295
    }
296
 
297
    /* Implicitly flush the buffered events on close. */
298
    $logger->close();
299
 
300
At this time, the ``flush()`` method is only implemented by `the console
301
handler`_, `the file handler`_, `the Firebug handler`_, and `the mail
302
handler`_.
303
 
304
 
305
Standard Log Handlers
306
=====================
307
 
308
The Console Handler
309
-------------------
310
The Console handler outputs log events directly to the console.  It supports
311
output buffering and configurable string formats.
312
 
313
Configuration
314
~~~~~~~~~~~~~
315
+-------------------+-----------+---------------+---------------------------+
316
| Parameter         | Type      | Default       | Description               |
317
+===================+===========+===============+===========================+
318
| ``stream``        | File      | STDOUT_       | The output stream to use. |
319
+-------------------+-----------+---------------+---------------------------+
320
| ``buffering``     | Boolean   | False         | Should the output be      |
321
|                   |           |               | buffered until shutdown?  |
322
+-------------------+-----------+---------------+---------------------------+
323
| ``lineFormat``    | String    | ``%1$s %2$s   | `Log line format`_        |
324
|                   |           | [%3$s] %4$s`` | specification.            |
325
+-------------------+-----------+---------------+---------------------------+
326
| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
327
|                   |           | %H:%M:%S``    | (for strftime_).          |
328
+-------------------+-----------+---------------+---------------------------+
329
 
330
.. _STDOUT: http://www.php.net/wrappers.php
331
.. _strftime: http://www.php.net/strftime
332
 
333
Example
334
~~~~~~~
335
::
336
 
337
    $logger = Log::singleton('console', '', 'ident');
338
    for ($i = 0; $i < 10; $i++) {
339
        $logger->log("Log entry $i");
340
    }
341
 
342
 
343
The Display Handler
344
-------------------
345
The Display handler simply prints the log events back to the browser.  It
346
respects the ``error_prepend_string`` and ``error_append_string`` `error
347
handling values`_ and is useful when `logging from standard error handlers`_.
348
 
349
Configuration
350
~~~~~~~~~~~~~
351
+-------------------+-----------+---------------+---------------------------+
352
| Parameter         | Type      | Default       | Description               |
353
+===================+===========+===============+===========================+
354
| ``lineFormat``    | String    | ``<b>%3$s</b>:| `Log line format`_        |
355
|                   |           | %4$s``        | specification.            |
356
+-------------------+-----------+---------------+---------------------------+
357
| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
358
|                   |           | %H:%M:%S``    | (for strftime_).          |
359
+-------------------+-----------+---------------+---------------------------+
360
| ``error_prepend`` | String    | PHP INI value | This string will be       |
361
|                   |           |               | prepended to the line     |
362
|                   |           |               | format.                   |
363
+-------------------+-----------+---------------+---------------------------+
364
| ``error_append``  | String    | PHP INI value | This string will be       |
365
|                   |           |               | appended to the line      |
366
|                   |           |               | format.                   |
367
+-------------------+-----------+---------------+---------------------------+
368
| ``linebreak``     | String    | ``<br />\n``  | This string is used to    |
369
|                   |           |               | represent a line break.   |
370
+-------------------+-----------+---------------+---------------------------+
371
| ``rawText``       | Boolean   | False         | Should message text be    |
372
|                   |           |               | passed directly to the log|
373
|                   |           |               | system?  Otherwise, it    |
374
|                   |           |               | will be converted to an   |
375
|                   |           |               | HTML-safe representation. |
376
+-------------------+-----------+---------------+---------------------------+
377
 
378
.. _error handling values: http://www.php.net/errorfunc
379
 
380
Example
381
~~~~~~~
382
::
383
 
384
    $conf = array('error_prepend' => '<font color="#ff0000"><tt>',
385
                  'error_append'  => '</tt></font>');
386
    $logger = Log::singleton('display', '', '', $conf, PEAR_LOG_DEBUG);
387
    for ($i = 0; $i < 10; $i++) {
388
        $logger->log("Log entry $i");
389
    }
390
 
391
 
392
The Error_Log Handler
393
---------------------
394
The Error_Log handler sends log events to PHP's `error_log()`_ function.
395
 
396
Configuration
397
~~~~~~~~~~~~~
398
+-------------------+-----------+---------------+---------------------------+
399
| Parameter         | Type      | Default       | Description               |
400
+===================+===========+===============+===========================+
401
| ``destination``   | String    | '' `(empty)`  | Optional destination value|
402
|                   |           |               | for `error_log()`_.  See  |
403
|                   |           |               | `Error_Log Types`_ for    |
404
|                   |           |               | more details.             |
405
+-------------------+-----------+---------------+---------------------------+
406
| ``extra_headers`` | String    | '' `(empty)`  | Additional headers to pass|
407
|                   |           |               | to the `mail()`_ function |
408
|                   |           |               | when the                  |
409
|                   |           |               | ``PEAR_LOG_TYPE_MAIL``    |
410
|                   |           |               | type is specified.        |
411
+-------------------+-----------+---------------+---------------------------+
412
| ``lineFormat``    | String    | ``%2$s: %4$s``| `Log line format`_        |
413
|                   |           |               | specification.            |
414
+-------------------+-----------+---------------+---------------------------+
415
| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
416
|                   |           | %H:%M:%S``    | (for strftime_).          |
417
+-------------------+-----------+---------------+---------------------------+
418
 
419
Error_Log Types
420
~~~~~~~~~~~~~~~
421
All of the available log types are detailed in the `error_log()`_ section of
422
the PHP manual.  For your convenience, the Log package also defines the
423
following constants that can be used for the ``$name`` handler construction
424
parameter.
425
 
426
+---------------------------+-----------------------------------------------+
427
| Constant                  | Description                                   |
428
+===========================+===============================================+
429
| ``PEAR_LOG_TYPE_SYSTEM``  | Log events are sent to PHP's system logger,   |
430
|                           | which uses the operating system's logging     |
431
|                           | mechanism or a file (depending on the value   |
432
|                           | of the `error_log configuration directive`_). |
433
+---------------------------+-----------------------------------------------+
434
| ``PEAR_LOG_TYPE_MAIL``    | Log events are sent via email to the address  |
435
|                           | specified in the ``destination`` value.       |
436
+---------------------------+-----------------------------------------------+
437
| ``PEAR_LOG_TYPE_DEBUG``   | Log events are sent through PHP's debugging   |
438
|                           | connection.  This will only work if           |
439
|                           | `remote debugging`_ has been enabled.  The    |
440
|                           | ``destination`` value is used to specify the  |
441
|                           | host name or IP address of the target socket. |
442
+---------------------------+-----------------------------------------------+
443
| ``PEAR_LOG_TYPE_FILE``    | Log events will be appended to the file named |
444
|                           | by the ``destination`` value.                 |
445
+---------------------------+-----------------------------------------------+
446
| ``PEAR_LOG_TYPE_SAPI``    | Log events will be sent directly to the SAPI  |
447
|                           | logging handler.                              |
448
+---------------------------+-----------------------------------------------+
449
 
450
.. _error_log(): http://www.php.net/error_log
451
.. _mail(): http://www.php.net/mail
452
.. _error_log configuration directive: http://www.php.net/errorfunc#ini.error-log
453
.. _remote debugging: http://www.php.net/install.configure#install.configure.enable-debugger
454
 
455
Example
456
~~~~~~~
457
::
458
 
459
    $logger = Log::singleton('error_log', PEAR_LOG_TYPE_SYSTEM, 'ident');
460
    for ($i = 0; $i < 10; $i++) {
461
        $logger->log("Log entry $i");
462
    }
463
 
464
 
465
The File Handler
466
----------------
467
The File handler writes log events to a text file using configurable string
468
formats.
469
 
470
Configuration
471
~~~~~~~~~~~~~
472
+-------------------+-----------+---------------+---------------------------+
473
| Parameter         | Type      | Default       | Description               |
474
+===================+===========+===============+===========================+
475
| ``append``        | Boolean   | True          | Should new log entries be |
476
|                   |           |               | append to an existing log |
477
|                   |           |               | file, or should the a new |
478
|                   |           |               | log file overwrite an     |
479
|                   |           |               | existing one?             |
480
+-------------------+-----------+---------------+---------------------------+
481
| ``locking``       | Boolean   | False         | Should advisory file      |
482
|                   |           |               | locking (using flock_) be |
483
|                   |           |               | used?                     |
484
+-------------------+-----------+---------------+---------------------------+
485
| ``mode``          | Integer   | 0644          | Octal representation of   |
486
|                   |           |               | the log file's permissions|
487
|                   |           |               | mode.                     |
488
+-------------------+-----------+---------------+---------------------------+
489
| ``dirmode``       | Integer   | 0755          | Octal representation of   |
490
|                   |           |               | the file permission mode  |
491
|                   |           |               | that will be used when    |
492
|                   |           |               | creating directories that |
493
|                   |           |               | do not already exist.     |
494
+-------------------+-----------+---------------+---------------------------+
495
| ``eol``           | String    | OS default    | The end-of-line character |
496
|                   |           |               | sequence.                 |
497
+-------------------+-----------+---------------+---------------------------+
498
| ``lineFormat``    | String    | ``%1$s %2$s   | `Log line format`_        |
499
|                   |           | [%3$s] %4$s`` | specification.            |
500
+-------------------+-----------+---------------+---------------------------+
501
| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
502
|                   |           | %H:%M:%S``    | (for strftime_).          |
503
+-------------------+-----------+---------------+---------------------------+
504
 
505
.. _flock: http://www.php.net/flock
506
.. _strftime: http://www.php.net/strftime
507
 
508
The file handler will only attempt to set the ``mode`` value if it was
509
responsible for creating the file.
510
 
511
Example
512
~~~~~~~
513
::
514
 
515
    $conf = array('mode' => 0600, 'timeFormat' => '%X %x');
516
    $logger = Log::singleton('file', 'out.log', 'ident', $conf);
517
    for ($i = 0; $i < 10; $i++) {
518
        $logger->log("Log entry $i");
519
    }
520
 
521
 
522
The Firebug Handler
523
-------------------
524
The Firebug handler outputs log events to the Firebug_ console. It supports
525
output buffering and configurable string formats.
526
 
527
Configuration
528
~~~~~~~~~~~~~
529
+-------------------+-----------+---------------+---------------------------+
530
| Parameter         | Type      | Default       | Description               |
531
+===================+===========+===============+===========================+
532
| ``buffering``     | Boolean   | False         | Should the output be      |
533
|                   |           |               | buffered until shutdown?  |
534
+-------------------+-----------+---------------+---------------------------+
535
| ``lineFormat``    | String    | ``%2$s [%3$s] | `Log line format`_        |
536
|                   |           | %4$s``        | specification.            |
537
+-------------------+-----------+---------------+---------------------------+
538
| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
539
|                   |           | %H:%M:%S``    | (for strftime_).          |
540
+-------------------+-----------+---------------+---------------------------+
541
 
542
.. _Firebug: http://www.getfirebug.com/
543
.. _strftime: http://www.php.net/strftime
544
 
545
Example
546
~~~~~~~
547
::
548
 
549
    $logger = Log::singleton('firebug', '', 'ident');
550
    for ($i = 0; $i < 10; $i++) {
551
        $logger->log("Log entry $i");
552
    }
553
 
554
 
555
The Mail Handler
556
----------------
557
 
558
The Mail handler aggregates a session's log events and sends them in the body
559
of an email message using either the `PEAR Mail`_ package or PHP's native
560
`mail()`_ function.
561
 
562
If an empty ``mailBackend`` value is specified, the `mail()`_ function will be
563
used instead of the `PEAR Mail`_ package.
564
 
565
Multiple recipients can be specified by separating their email addresses with
566
commas in the ``$name`` construction parameter.
567
 
568
Configuration
569
~~~~~~~~~~~~~
570
+-------------------+-----------+---------------+---------------------------+
571
| Parameter         | Type      | Default       | Description               |
572
+===================+===========+===============+===========================+
573
| ``from``          | String    | sendmail_from | Value for the message's   |
574
|                   |           | INI value     | ``From:`` header.         |
575
+-------------------+-----------+---------------+---------------------------+
576
| ``subject``       | String    | ``[Log_mail]  | Value for the message's   |
577
|                   |           | Log message`` | ``Subject:`` header.      |
578
+-------------------+-----------+---------------+---------------------------+
579
| ``preamble``      | String    | `` `(empty)`  | Preamble for the message. |
580
+-------------------+-----------+---------------+---------------------------+
581
| ``lineFormat``    | String    | ``%1$s %2$s   | `Log line format`_        |
582
|                   |           | [%3$s] %4$s`` | specification.            |
583
+-------------------+-----------+---------------+---------------------------+
584
| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
585
|                   |           | %H:%M:%S``    | (for strftime_).          |
586
+-------------------+-----------+---------------+---------------------------+
587
| ``mailBackend``   | String    | `` `(empty)`  | Name of the Mail package  |
588
|                   |           |               | backend to use.           |
589
+-------------------+-----------+---------------+---------------------------+
590
| ``mailParams``    | Array     | `(empty)`     | Array of parameters that  |
591
|                   |           |               | will be passed to the     |
592
|                   |           |               | Mail package backend.     |
593
+-------------------+-----------+---------------+---------------------------+
594
 
595
.. _PEAR Mail: http://pear.php.net/package/Mail
596
.. _mail(): http://www.php.net/mail
597
 
598
Example
599
~~~~~~~
600
::
601
 
602
    $conf = array('subject' => 'Important Log Events');
603
    $logger = Log::singleton('mail', 'webmaster@example.com', 'ident', $conf);
604
    for ($i = 0; $i < 10; $i++) {
605
        $logger->log("Log entry $i");
606
    }
607
 
608
 
609
The MDB2 Handler
610
----------------
611
The MDB2 handler is similar to `the SQL (DB) handler`_, but instead of using
612
the PEAR DB package, it uses the `MDB2 database abstraction package`_.
613
 
614
Configuration
615
~~~~~~~~~~~~~
616
+-------------------+-----------+---------------+---------------------------+
617
| Parameter         | Type      | Default       | Description               |
618
+===================+===========+===============+===========================+
619
| ``dsn``           | Mixed     | '' `(empty)`  | A `Data Source Name`_.    |
620
|                   |           |               | |required|                |
621
+-------------------+-----------+---------------+---------------------------+
622
| ``options``       | Array     | ``persistent``| An array of `MDB2`_       |
623
|                   |           |               | options.                  |
624
+-------------------+-----------+---------------+---------------------------+
625
| ``db``            | Object    | NULL          | An existing `MDB2`_       |
626
|                   |           |               | object.  If specified,    |
627
|                   |           |               | this object will be used, |
628
|                   |           |               | and ``dsn`` will be       |
629
|                   |           |               | ignored.                  |
630
+-------------------+-----------+---------------+---------------------------+
631
| ``sequence``      | String    | ``log_id``    | The name of the sequence  |
632
|                   |           |               | to use when generating    |
633
|                   |           |               | unique event IDs.   Under |
634
|                   |           |               | many databases, this will |
635
|                   |           |               | be used as the name of    |
636
|                   |           |               | the sequence table.       |
637
+-------------------+-----------+---------------+---------------------------+
638
| ``identLimit``    | Integer   | 16            | The maximum length of the |
639
|                   |           |               | ``ident`` string.         |
640
|                   |           |               | **Changing this value may |
641
|                   |           |               | require updates to the SQL|
642
|                   |           |               | schema, as well.**        |
643
+-------------------+-----------+---------------+---------------------------+
644
| ``singleton``     | Boolean   | false         | Is true, use a singleton  |
645
|                   |           |               | database object using     |
646
|                   |           |               | `MDB2::singleton()`_.     |
647
+-------------------+-----------+---------------+---------------------------+
648
 
649
.. _MDB2: http://pear.php.net/package/MDB2
650
.. _MDB2 database abstraction package: MDB2_
651
.. _MDB2::singleton(): http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2.html#methodsingleton
652
 
653
The Null Handler
654
----------------
655
The Null handler simply consumes log events (akin to sending them to
656
``/dev/null``).  `Log level masks`_ are respected, and the event will still be
657
sent to any registered `log observers`_.
658
 
659
Example
660
~~~~~~~
661
::
662
 
663
    $logger = Log::singleton('null');
664
    for ($i = 0; $i < 10; $i++) {
665
        $logger->log("Log entry $i");
666
    }
667
 
668
 
669
The SQL (DB) Handler
670
--------------------
671
 
672
The SQL handler sends log events to a database using `PEAR's DB abstraction
673
layer`_.
674
 
675
**Note:** Due to the constraints of the default database schema, the SQL
676
handler limits the length of the ``$ident`` string to sixteen (16) characters.
677
This limit can be adjusted using the ``identLimit`` configuration parameter.
678
 
679
The Log Table
680
~~~~~~~~~~~~~
681
The default SQL table used by this handler looks like this::
682
 
683
    CREATE TABLE log_table (
684
        id          INT NOT NULL,
685
        logtime     TIMESTAMP NOT NULL,
686
        ident       CHAR(16) NOT NULL,
687
        priority    INT NOT NULL,
688
        message     VARCHAR(200),
689
        PRIMARY KEY (id)
690
    );
691
 
692
This is the "lowest common denominator" that should work across all SQL
693
compliant database.  You may want to make database- or site-specific changes
694
to this schema to support your specific needs, however.  For example,
695
`PostgreSQL`_ users may prefer to use a ``TEXT`` type for the ``message``
696
field.
697
 
698
.. _PostgreSQL: http://www.postgresql.org/
699
 
700
Configuration
701
~~~~~~~~~~~~~
702
+-------------------+-----------+---------------+---------------------------+
703
| Parameter         | Type      | Default       | Description               |
704
+===================+===========+===============+===========================+
705
| ``dsn``           | Mixed     | '' `(empty)`  | A `Data Source Name`_.    |
706
|                   |           |               | |required|                |
707
+-------------------+-----------+---------------+---------------------------+
708
| ``sql``           | String    | |sql-default| | SQL insertion statement.  |
709
+-------------------+-----------+---------------+---------------------------+
710
| ``options``       | Array     | ``persistent``| An array of `DB`_ options.|
711
+-------------------+-----------+---------------+---------------------------+
712
| ``db``            | Object    | NULL          | An existing `DB`_ object. |
713
|                   |           |               | If specified, this object |
714
|                   |           |               | will be used, and ``dsn`` |
715
|                   |           |               | will be ignored.          |
716
+-------------------+-----------+---------------+---------------------------+
717
| ``sequence``      | String    | ``log_id``    | The name of the sequence  |
718
|                   |           |               | to use when generating    |
719
|                   |           |               | unique event IDs.   Under |
720
|                   |           |               | many databases, this will |
721
|                   |           |               | be used as the name of    |
722
|                   |           |               | the sequence table.       |
723
+-------------------+-----------+---------------+---------------------------+
724
| ``identLimit``    | Integer   | 16            | The maximum length of the |
725
|                   |           |               | ``ident`` string.         |
726
|                   |           |               | **Changing this value may |
727
|                   |           |               | require updates to the SQL|
728
|                   |           |               | schema, as well.**        |
729
+-------------------+-----------+---------------+---------------------------+
730
 
731
The name of the database table to which the log entries will be written is
732
specified using the ``$name`` construction parameter (see `Configuring a
733
Handler`_).
734
 
735
.. |sql-default| replace:: ``INSERT INTO $table (id, logtime, ident, priority, message) VALUES(?, CURRENT_TIMESTAMP, ?, ?, ?)``
736
 
737
.. _DB: http://pear.php.net/package/DB
738
.. _PEAR's DB abstraction layer: DB_
739
.. _Data Source Name: http://pear.php.net/manual/en/package.database.db.intro-dsn.php
740
 
741
Examples
742
~~~~~~~~
743
Using a `Data Source Name`_ to create a new database connection::
744
 
745
    $conf = array('dsn' => 'pgsql://jon@localhost+unix/logs');
746
    $logger = Log::singleton('sql', 'log_table', 'ident', $conf);
747
    for ($i = 0; $i < 10; $i++) {
748
        $logger->log("Log entry $i");
749
    }
750
 
751
Using an existing `DB`_ object::
752
 
753
    require_once 'DB.php';
754
    $db = &DB::connect('pgsql://jon@localhost+unix/logs');
755
 
756
    $conf['db'] = $db;
757
    $logger = Log::singleton('sql', 'log_table', 'ident', $conf);
758
    for ($i = 0; $i < 10; $i++) {
759
        $logger->log("Log entry $i");
760
    }
761
 
762
 
763
The Sqlite Handler
764
------------------
765
:Author:        Bertrand Mansion
766
 
767
The Sqlite handler sends log events to an Sqlite database using the `native
768
PHP sqlite functions`_.
769
 
770
It is faster than `the SQL (DB) handler`_ because requests are made directly
771
to the database without using an abstraction layer.  It is also interesting to
772
note that Sqlite database files can be moved, copied, and deleted on your
773
system just like any other files, which makes log management easier.  Last but
774
not least, using a database to log your events allows you to use SQL queries
775
to create reports and statistics.
776
 
777
When using a database and logging a lot of events, it is recommended to split
778
the database into smaller databases.  This is allowed by Sqlite, and you can
779
later use the Sqlite `ATTACH`_ statement to query your log database files
780
globally.
781
 
782
If the database does not exist when the log is opened, sqlite will try to
783
create it automatically. If the log table does not exist, it will also be
784
automatically created.  The table creation uses the following SQL request::
785
 
786
    CREATE TABLE log_table (
787
        id          INTEGER PRIMARY KEY NOT NULL,
788
        logtime     NOT NULL,
789
        ident       CHAR(16) NOT NULL,
790
        priority    INT NOT NULL,
791
        message
792
    );
793
 
794
Configuration
795
~~~~~~~~~~~~~
796
+-------------------+-----------+---------------+---------------------------+
797
| Parameter         | Type      | Default       | Description               |
798
+===================+===========+===============+===========================+
799
| ``filename``      | String    | '' `(empty)`  | Path to an Sqlite         |
800
|                   |           |               | database. |required|      |
801
+-------------------+-----------+---------------+---------------------------+
802
| ``mode``          | Integer   | 0666          | Octal mode used to open   |
803
|                   |           |               | the database.             |
804
+-------------------+-----------+---------------+---------------------------+
805
| ``persistent``    | Boolean   | false         | Use a persistent          |
806
|                   |           |               | connection.               |
807
+-------------------+-----------+---------------+---------------------------+
808
 
809
An already opened database connection can also be passed as parameter instead
810
of the above configuration.  In this case, closing the database connection is
811
up to the user.
812
 
813
.. _native PHP sqlite functions: http://www.php.net/sqlite
814
.. _ATTACH: http://www.sqlite.org/lang.html#attach
815
 
816
Examples
817
~~~~~~~~
818
Using a configuration to create a new database connection::
819
 
820
    $conf = array('filename' => 'log.db', 'mode' => 0666, 'persistent' => true);
821
    $logger = Log::factory('sqlite', 'log_table', 'ident', $conf);
822
    $logger->log('logging an event', PEAR_LOG_WARNING);
823
 
824
Using an existing connection::
825
 
826
    $db = sqlite_open('log.db', 0666, $error);
827
    $logger = Log::factory('sqlite', 'log_table', 'ident', $db);
828
    $logger->log('logging an event', PEAR_LOG_WARNING);
829
    sqlite_close($db);
830
 
831
 
832
The Syslog Handler
833
------------------
834
The Syslog handler sends log events to the system logging service (syslog on
835
Unix-like environments or the Event Log on Windows systems).  The events are
836
sent using PHP's `syslog()`_ function.
837
 
838
Configuration
839
~~~~~~~~~~~~~
840
+-------------------+-----------+---------------+---------------------------+
841
| Parameter         | Type      | Default       | Description               |
842
+===================+===========+===============+===========================+
843
| ``inherit``       | Boolean   | false         | Inherit the current syslog|
844
|                   |           |               | connection for this       |
845
|                   |           |               | process, or start a new   |
846
|                   |           |               | one via `openlog()`_?     |
847
+-------------------+-----------+---------------+---------------------------+
848
| ``reopen``        | Boolean   | false         | Reopen the syslog         |
849
|                   |           |               | connection for each log   |
850
|                   |           |               | event?                    |
851
+-------------------+-----------+---------------+---------------------------+
852
| ``maxLength``     | Integer   | 500           | Maximum message length    |
853
|                   |           |               | that will be sent to the  |
854
|                   |           |               | `syslog()`_ function.     |
855
|                   |           |               | Longer messages will be   |
856
|                   |           |               | split across multiple     |
857
|                   |           |               | `syslog()`_ calls.        |
858
+-------------------+-----------+---------------+---------------------------+
859
| ``lineFormat``    | String    | ``%4$s``      | `Log line format`_        |
860
|                   |           |               | specification.            |
861
+-------------------+-----------+---------------+---------------------------+
862
| ``timeFormat``    | String    | ``%b %d       | Time stamp format         |
863
|                   |           | %H:%M:%S``    | (for strftime_).          |
864
+-------------------+-----------+---------------+---------------------------+
865
 
866
Facilities
867
~~~~~~~~~~
868
+-------------------+-------------------------------------------------------+
869
| Constant          | Category Description                                  |
870
+===================+=======================================================+
871
| ``LOG_AUTH``      | Security / authorization messages; ``LOG_AUTHPRIV`` is|
872
|                   | preferred on systems where it is defined.             |
873
+-------------------+-------------------------------------------------------+
874
| ``LOG_AUTHPRIV``  | Private security / authorization messages             |
875
+-------------------+-------------------------------------------------------+
876
| ``LOG_CRON``      | Clock daemon (``cron`` and ``at``)                    |
877
+-------------------+-------------------------------------------------------+
878
| ``LOG_DAEMON``    | System daemon processes                               |
879
+-------------------+-------------------------------------------------------+
880
| ``LOG_KERN``      | Kernel messages                                       |
881
+-------------------+-------------------------------------------------------+
882
| ``LOG_LOCAL0`` .. | Reserved for local use; **not** available under       |
883
| ``LOG_LOCAL7``    | Windows.                                              |
884
+-------------------+-------------------------------------------------------+
885
| ``LOG_LPR``       | Printer subsystem                                     |
886
+-------------------+-------------------------------------------------------+
887
| ``LOG_MAIL``      | Mail subsystem                                        |
888
+-------------------+-------------------------------------------------------+
889
| ``LOG_NEWS``      | USENET news subsystem                                 |
890
+-------------------+-------------------------------------------------------+
891
| ``LOG_SYSLOG``    | Internal syslog messages                              |
892
+-------------------+-------------------------------------------------------+
893
| ``LOG_USER``      | Generic user-level messages                           |
894
+-------------------+-------------------------------------------------------+
895
| ``LOG_UUCP``      | UUCP subsystem                                        |
896
+-------------------+-------------------------------------------------------+
897
 
898
.. _syslog(): http://www.php.net/syslog
899
.. _openlog(): http://www.php.net/openlog
900
 
901
Example
902
~~~~~~~
903
::
904
 
905
    $logger = Log::singleton('syslog', LOG_LOCAL0, 'ident');
906
    for ($i = 0; $i < 10; $i++) {
907
        $logger->log("Log entry $i");
908
    }
909
 
910
 
911
The Window Handler
912
------------------
913
The Window handler sends log events to a separate browser window.  The
914
original idea for this handler was inspired by Craig Davis' Zend.com article
915
entitled `"JavaScript Power PHP Debugging"`_.
916
 
917
Configuration
918
~~~~~~~~~~~~~
919
+-------------------+-----------+---------------+---------------------------+
920
| Parameter         | Type      | Default       | Description               |
921
+===================+===========+===============+===========================+
922
| ``title``         | String    | ``Log Output  | The title of the output   |
923
|                   |           | Window``      | window.                   |
924
+-------------------+-----------+---------------+---------------------------+
925
| ``styles``        | Array     | `ROY G BIV`_  | Mapping of log priorities |
926
|                   |           | (high to low) | to CSS styles.            |
927
+-------------------+-----------+---------------+---------------------------+
928
 
929
**Note:** The Window handler may not work reliably when PHP's `output
930
buffering`_ system is enabled.
931
 
932
.. _"JavaScript Power PHP Debugging": http://www.zend.com/zend/tut/tutorial-DebugLib.php
933
.. _ROY G BIV: http://www.cis.rit.edu/
934
.. _output buffering: http://www.php.net/outcontrol
935
 
936
Example
937
~~~~~~~
938
::
939
 
940
    $conf = array('title' => 'Sample Log Output');
941
    $logger = Log::singleton('win', 'LogWindow', 'ident', $conf);
942
    for ($i = 0; $i < 10; $i++) {
943
        $logger->log("Log entry $i");
944
    }
945
 
946
 
947
Composite Handlers
948
==================
949
It is often useful to log events to multiple handlers.  The Log package
950
provides a compositing system that marks this task trivial.
951
 
952
Start by creating the individual log handlers::
953
 
954
    $console = Log::singleton('console', '', 'TEST');
955
    $file = Log::singleton('file', 'out.log', 'TEST');
956
 
957
Then, construct a composite handler and add the individual handlers as
958
children of the composite::
959
 
960
    $composite = Log::singleton('composite');
961
    $composite->addChild($console);
962
    $composite->addChild($file);
963
 
964
The composite handler implements the standard ``Log`` interface so you can use
965
it just like any of the other handlers::
966
 
967
    $composite->log('This event will be logged to both handlers.');
968
 
969
Children can be removed from the composite when they're not longer needed::
970
 
971
    $composite->removeChild($file);
972
 
973
 
974
Log Observers
975
=============
976
Log observers provide an implementation of the `observer pattern`_.  In the
977
content of the Log package, they provide a mechanism by which you can examine
978
(i.e. observe) each event as it is logged.  This allows the implementation of
979
special behavior based on the contents of a log event.  For example, the
980
observer code could send an alert email if a log event contained the string
981
``PANIC``.
982
 
983
Creating a log observer involves implementing a subclass of the
984
``Log_observer`` class.  The subclass must override the base class's
985
``notify()`` method.  This method is passed a hash containing the event's
986
priority and event.  The subclass's implementation is free to act upon this
987
information in any way it likes.
988
 
989
Log observers are attached to ``Log`` instances via the ``attach()`` method::
990
 
991
    $observer = Log_observer::factory('yourType');
992
    $logger->attach($observer);
993
 
994
Observers can be detached using the ``detach()`` method::
995
 
996
    $logger->detach($observer);
997
 
998
At this time, no concrete ``Log_observer`` implementations are distributed
999
with the Log package.
1000
 
1001
.. _observer pattern: http://wikipedia.org/wiki/Observer_pattern
1002
 
1003
 
1004
Logging From Standard Error Handlers
1005
====================================
1006
 
1007
Logging PHP Errors
1008
------------------
1009
PHP's default error handler can be overridden using the `set_error_handler()`_
1010
function.  The custom error handling function can use a global Log instance to
1011
log the PHP errors.
1012
 
1013
**Note:** Fatal PHP errors cannot be handled by a custom error handler at this
1014
time.
1015
 
1016
::
1017
 
1018
    function errorHandler($code, $message, $file, $line)
1019
    {
1020
        global $logger;
1021
 
1022
        /* Map the PHP error to a Log priority. */
1023
        switch ($code) {
1024
        case E_WARNING:
1025
        case E_USER_WARNING:
1026
            $priority = PEAR_LOG_WARNING;
1027
            break;
1028
        case E_NOTICE:
1029
        case E_USER_NOTICE:
1030
            $priority = PEAR_LOG_NOTICE;
1031
            break;
1032
        case E_ERROR:
1033
        case E_USER_ERROR:
1034
            $priority = PEAR_LOG_ERR;
1035
            break;
1036
        default:
1037
            $priority = PEAR_LOG_INFO;
1038
        }
1039
 
1040
        $logger->log($message . ' in ' . $file . ' at line ' . $line,
1041
                     $priority);
1042
    }
1043
 
1044
    set_error_handler('errorHandler');
1045
    trigger_error('This is an information log message.', E_USER_NOTICE);
1046
 
1047
.. _set_error_handler(): http://www.php.net/set_error_handler
1048
 
1049
Logging PHP Assertions
1050
----------------------
1051
PHP allows user-defined `assert()`_ callback handlers.  The assertion callback
1052
is configured using the `assert_options()`_ function.
1053
 
1054
::
1055
 
1056
    function assertCallback($file, $line, $message)
1057
    {
1058
        global $logger;
1059
 
1060
        $logger->log($message . ' in ' . $file . ' at line ' . $line,
1061
                     PEAR_LOG_ALERT);
1062
    }
1063
 
1064
    assert_options(ASSERT_CALLBACK, 'assertCallback');
1065
    assert(false);
1066
 
1067
.. _assert(): http://www.php.net/assert
1068
.. _assert_options(): http://www.php.net/assert_options
1069
 
1070
Logging PHP Exceptions
1071
----------------------
1072
PHP 5 and later support the concept of `exceptions`_.  A custom exception
1073
handler can be assigned using the `set_exception_handler()`_ function.
1074
 
1075
::
1076
 
1077
    function exceptionHandler($exception)
1078
    {
1079
        global $logger;
1080
 
1081
        $logger->log($exception->getMessage(), PEAR_LOG_ALERT);
1082
    }
1083
 
1084
    set_exception_handler('exceptionHandler');
1085
    throw new Exception('Uncaught Exception');
1086
 
1087
.. _exceptions: http://www.php.net/exceptions
1088
.. _set_exception_handler(): http://www.php.net/set_exception_handler
1089
 
1090
Logging PEAR Errors
1091
-------------------
1092
The Log package can be used with `PEAR::setErrorHandling()`_'s
1093
``PEAR_ERROR_CALLBACK`` mechanism by writing an error handling function that
1094
uses a global Log instance.  Here's an example::
1095
 
1096
    function errorHandler($error)
1097
    {
1098
        global $logger;
1099
 
1100
        $message = $error->getMessage();
1101
 
1102
        if (!empty($error->backtrace[1]['file'])) {
1103
            $message .= ' (' . $error->backtrace[1]['file'];
1104
            if (!empty($error->backtrace[1]['line'])) {
1105
                $message .= ' at line ' . $error->backtrace[1]['line'];
1106
            }
1107
            $message .= ')';
1108
        }
1109
 
1110
        $logger->log($message, $error->code);
1111
    }
1112
 
1113
    PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'errorHandler');
1114
    PEAR::raiseError('This is an information log message.', PEAR_LOG_INFO);
1115
 
1116
.. _PEAR::setErrorHandling(): http://pear.php.net/manual/en/core.pear.pear.seterrorhandling.php
1117
 
1118
 
1119
Custom Handlers
1120
===============
1121
There are times when the standard handlers aren't a perfect match for your
1122
needs.  In those situations, the solution might be to write a custom handler.
1123
 
1124
Using a Custom Handler
1125
----------------------
1126
Using a custom Log handler is very simple.  Once written (see `Writing New
1127
Handlers`_ and `Extending Existing Handlers`_ below), you have the choice of
1128
placing the file in your PEAR installation's main ``Log/`` directory (usually
1129
something like ``/usr/local/lib/php/Log`` or ``C:\php\pear\Log``), where it
1130
can be found and use by any PHP application on the system, or placing the file
1131
somewhere in your application's local hierarchy and including it before the
1132
the custom Log object is constructed.
1133
 
1134
Method 1: Handler in the Standard Location
1135
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1136
After copying the handler file to your PEAR installation's ``Log/`` directory,
1137
simply treat the handler as if it were part of the standard distributed.  If
1138
your handler is named ``custom`` (and therefore implemented by a class named
1139
``Log_custom``)::
1140
 
1141
    require_once 'Log.php';
1142
 
1143
    $logger = Log::factory('custom', '', 'CUSTOM');
1144
 
1145
 
1146
Method 2: Handler in a Custom Location
1147
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1148
If you prefer storing your handler in your application's local hierarchy,
1149
you'll need to include that file before you can create a Log instance based on
1150
it.
1151
 
1152
::
1153
 
1154
    require_once 'Log.php';
1155
    require_once 'LocalHandlers/custom.php';
1156
 
1157
    $logger = Log::factory('custom', '', 'CUSTOM');
1158
 
1159
 
1160
Writing New Handlers
1161
--------------------
1162
Writing a new Log handler is as simple as authoring a new class that extends
1163
the ``Log`` class and that implements a relatively small set of standard
1164
methods.
1165
 
1166
Every handler's class name must start with ``Log_`` in order for it to be
1167
recognized by the Log package.
1168
 
1169
::
1170
 
1171
    class Log_custom extends Log
1172
 
1173
The handler's constructor will be called with four parameters.  These values
1174
are discussed in detail in the `Configuring a Handler`_ section.
1175
 
1176
::
1177
 
1178
    Log_custom($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG)
1179
 
1180
The constructor is responsible for configuring the handler based on these
1181
values.  Handler-specific parameters are passed as part of the ``$conf``
1182
array.  At a minimum, the handler's constructor must set the following values
1183
defined by the ``Log`` base class::
1184
 
1185
        $this->_id = md5(microtime());
1186
        $this->_name = $name;
1187
        $this->_ident = $ident;
1188
        $this->_mask = Log::UPTO($level);
1189
 
1190
The `Handler Methods`_ section below details the various standard methods that
1191
can be implemented by a log handler.  The `Utility Methods`_ section describes
1192
some useful utility methods provided by the ``Log`` base class which may be
1193
useful when implementing a log handler.
1194
 
1195
 
1196
Extending Existing Handlers
1197
---------------------------
1198
Extending existing handlers is very similar to `writing new handlers`_ with
1199
the exception that, instead of inheriting from the ``Log`` base class
1200
directly, the handler extends an existing handler's class.  This is a useful
1201
way of adding some custom behavior to an existing handler without writing an
1202
entirely new class (in the spirit of object-oriented programming).
1203
 
1204
For example, `the mail handler`_ could be extended to support sending messages
1205
with MIME-encoded attachments simply by authoring a new ``Log_mail_mime``
1206
class with a compliant constructor and a custom ``log()`` method.  The rest of
1207
the standard methods would fall back on the ``Log_mail`` base class's
1208
implementations.
1209
 
1210
Obviously, the specific details involved in extending an existing handler
1211
require a good working understanding of that handler's implementation.
1212
 
1213
 
1214
Handler Methods
1215
---------------
1216
 
1217
bool open()
1218
~~~~~~~~~~~
1219
The ``open()`` method is called to open the log resource for output.  Handlers
1220
can call ``open()`` immediately upon construction or lazily at runtime
1221
(perhaps when the first log event is received).
1222
 
1223
The ``Log`` base class provides a protected ``$_opened`` member variable which
1224
should be set to ``true`` when the log handler is opened and ``false`` when it
1225
is closed.  Handler methods can inspect this value to determine whether or not
1226
the handler is currently open and ready for output.
1227
 
1228
If the ``open()`` method fails to ready the handler for output, it should
1229
return ``false`` and set ``$this->_opened`` to ``false``.
1230
 
1231
bool close()
1232
~~~~~~~~~~~~
1233
The ``close()`` method is called to close the log resource.  This method is
1234
the analog of the ``open()`` method.  It should be safe to call ``close()``
1235
even when the handler is not open for output.
1236
 
1237
If the ``close()`` method fails to close the handler, it should return
1238
``false``.  Otherwise, it should return ``true``.  The ``$this->_opened``
1239
flag should also be updated appropriately.
1240
 
1241
bool flush()
1242
~~~~~~~~~~~~
1243
The ``flush()`` method flushes any buffered log events, as described in
1244
`Flushing Log Events`_.  The implementation of this method will be largely
1245
handler-specific.  If the handler does not support buffered output,
1246
implementing this method is not necessary; the ``Log`` class's ``flush()``
1247
method will be called instead.
1248
 
1249
bool log($message, $priority = null)
1250
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1251
The ``log()`` method is the core of every log handler.  It is called whenever
1252
the user wishes to log an event.  The implementation of this method is very
1253
handler-specific.  It should return ``true`` or ``false``, depending on
1254
whether or not the message was successfully logged by the handler.
1255
 
1256
The ``log()`` implementation should be sure to call `_announce()`__ whenever
1257
an event is successfully logged.
1258
 
1259
.. __: `void _announce($event)`_
1260
 
1261
Utility Methods
1262
---------------
1263
These utility methods are provided by the ``Log`` base class and provide
1264
common, useful functionality to handler implementations.
1265
 
1266
string _extractMessage($message)
1267
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1268
This method returns the string representation of the provided message data.
1269
 
1270
If ``$message`` is an object, ``_extractMessage()`` will attempt to extract
1271
the message text using a known method (such as a `PEAR_Error`_ object's
1272
`getMessage()`_ method).  If a known method, cannot be found, the serialized
1273
representation of the object will be returned.
1274
 
1275
If the message data is already a string, it will be returned unchanged.
1276
 
1277
.. _PEAR_Error: http://pear.php.net/manual/en/core.pear.pear-error.php
1278
.. _getMessage(): http://pear.php.net/manual/en/core.pear.pear-error.getmessage.php
1279
 
1280
string _format($format, $timestamp, $priority, $message)
1281
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1282
This method produces a formatted log line based on a format string and a set
1283
of `tokens`_ representing the current log record and state.
1284
 
1285
.. _tokens: `Log Line Format`_
1286
 
1287
bool _isMasked($priority)
1288
~~~~~~~~~~~~~~~~~~~~~~~~~
1289
This method checks if the given priority is included in the handler's current
1290
level mask.  This is useful for determining whether or not a log event should
1291
be written to the handler's log.
1292
 
1293
void _announce($event)
1294
~~~~~~~~~~~~~~~~~~~~~~
1295
This method informs any registered `log observers`_ that a new event has been
1296
logged.  ``$event`` is an array containing two named elements::
1297
 
1298
    array('priority' => $priority, 'message' => $message)
1299
 
1300
``_announce()`` should be called from a handler's `log()`_ method whenever an
1301
event is successfully logged.  Otherwise, registered observers will never
1302
become aware of the event.
1303
 
1304
.. _log(): `bool log($message, $priority = null)`_
1305
 
1306
.. |required| replace:: **[required]**
1307
 
1308
.. vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab textwidth=78 ft=rst: