PageRenderTime 91ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

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

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