PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/library/3rdParty/Log/docs/guide.txt

https://bitbucket.org/aradlein/shareplaylists
Plain Text | 1282 lines | 1017 code | 265 blank | 0 comment | 0 complexity | a7639430902ae1c883efa9167365d8fc MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, MIT

Large files files are truncated, but you can click here to view the full file

  1. =================
  2. The Log Package
  3. =================
  4. --------------------
  5. User Documentation
  6. --------------------
  7. :Author: Jon Parise
  8. :Contact: jon@php.net
  9. :Date: $Date: 2008/11/19 05:12:26 $
  10. :Revision: $Revision: 1.41 $
  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/viewvc.cgi/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://wikipedia.org/wiki/Factory_method_pattern
  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://wikipedia.org/wiki/Singleton_pattern
  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 excluding 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. Log Line Format
  184. ---------------
  185. Most log handlers support configurable line formats. The following is a list
  186. of special tokens that will be expanded at runtime with contextual information
  187. related to the log event. Each token has an alternate shorthand notation, as
  188. well.
  189. +------------------+-----------+--------------------------------------------+
  190. | Token | Alternate | Description |
  191. +==================+===========+============================================+
  192. | ``%{timestamp}`` | ``%1$s`` | Timestamp. This is often configurable. |
  193. +------------------+-----------+--------------------------------------------+
  194. | ``%{ident}`` | ``%2$s`` | The log handler's identification string. |
  195. +------------------+-----------+--------------------------------------------+
  196. | ``%{priority}`` | ``%3$s`` | The log event's priority. |
  197. +------------------+-----------+--------------------------------------------+
  198. | ``%{message}`` | ``%4$s`` | The log event's message text. |
  199. +------------------+-----------+--------------------------------------------+
  200. | ``%{file}`` | ``%5$s`` | The full filename of the logging file. |
  201. +------------------+-----------+--------------------------------------------+
  202. | ``%{line}`` | ``%6$s`` | The line number on which the event occured.|
  203. +------------------+-----------+--------------------------------------------+
  204. | ``%{function}`` | ``%7$s`` | The function from which the event occurred.|
  205. +------------------+-----------+--------------------------------------------+
  206. | ``%{class}`` | ``%8$s`` | The class in which the event occurred. |
  207. +------------------+-----------+--------------------------------------------+
  208. Flushing Log Events
  209. -------------------
  210. Some log handlers (such as `the console handler`_) support explicit
  211. "buffering". When buffering is enabled, log events won't actually be written
  212. to the output stream until the handler is closed. Other handlers (such as
  213. `the file handler`_) support implicit buffering because they use the operating
  214. system's IO routines, which may buffer the output.
  215. It's possible to force these handlers to flush their output, however, by
  216. calling their ``flush()`` method::
  217. $conf = array('buffering' => true);
  218. $logger = &Log::singleton('console', '', 'test', $conf);
  219. for ($i = 0; $i < 10; $i++) {
  220. $logger->log('This event will be buffered.');
  221. }
  222. /* Flush all of the buffered log events. */
  223. $logger->flush();
  224. for ($i = 0; $i < 10; $i++) {
  225. $logger->log('This event will be buffered.');
  226. }
  227. /* Implicitly flush the buffered events on close. */
  228. $logger->close();
  229. At this time, the ``flush()`` method is only implemented by `the console
  230. handler`_, `the file handler`_, `the Firebug handler`_, and `the mail
  231. handler`_.
  232. Standard Log Handlers
  233. =====================
  234. The Console Handler
  235. -------------------
  236. The Console handler outputs log events directly to the console. It supports
  237. output buffering and configurable string formats.
  238. Configuration
  239. ~~~~~~~~~~~~~
  240. +-------------------+-----------+---------------+---------------------------+
  241. | Parameter | Type | Default | Description |
  242. +===================+===========+===============+===========================+
  243. | ``stream`` | File | STDOUT_ | The output stream to use. |
  244. +-------------------+-----------+---------------+---------------------------+
  245. | ``buffering`` | Boolean | False | Should the output be |
  246. | | | | buffered until shutdown? |
  247. +-------------------+-----------+---------------+---------------------------+
  248. | ``lineFormat`` | String | ``%1$s %2$s | `Log line format`_ |
  249. | | | [%3$s] %4$s`` | specification. |
  250. +-------------------+-----------+---------------+---------------------------+
  251. | ``timeFormat`` | String | ``%b %d | Time stamp format |
  252. | | | %H:%M:%S`` | (for strftime_). |
  253. +-------------------+-----------+---------------+---------------------------+
  254. .. _STDOUT: http://www.php.net/wrappers.php
  255. .. _strftime: http://www.php.net/strftime
  256. Example
  257. ~~~~~~~
  258. ::
  259. $logger = &Log::singleton('console', '', 'ident');
  260. for ($i = 0; $i < 10; $i++) {
  261. $logger->log("Log entry $i");
  262. }
  263. The Display Handler
  264. -------------------
  265. The Display handler simply prints the log events back to the browser. It
  266. respects the ``error_prepend_string`` and ``error_append_string`` `error
  267. handling values`_ and is useful when `logging from standard error handlers`_.
  268. Configuration
  269. ~~~~~~~~~~~~~
  270. +-------------------+-----------+---------------+---------------------------+
  271. | Parameter | Type | Default | Description |
  272. +===================+===========+===============+===========================+
  273. | ``lineFormat`` | String | ``<b>%3$s</b>:| `Log line format`_ |
  274. | | | %4$s`` | specification. |
  275. +-------------------+-----------+---------------+---------------------------+
  276. | ``timeFormat`` | String | ``%b %d | Time stamp format |
  277. | | | %H:%M:%S`` | (for strftime_). |
  278. +-------------------+-----------+---------------+---------------------------+
  279. | ``error_prepend`` | String | PHP INI value | This string will be |
  280. | | | | prepended to the line |
  281. | | | | format. |
  282. +-------------------+-----------+---------------+---------------------------+
  283. | ``error_append`` | String | PHP INI value | This string will be |
  284. | | | | appended to the line |
  285. | | | | format. |
  286. +-------------------+-----------+---------------+---------------------------+
  287. | ``linebreak`` | String | ``<br />\n`` | This string is used to |
  288. | | | | represent a line break. |
  289. +-------------------+-----------+---------------+---------------------------+
  290. .. _error handling values: http://www.php.net/errorfunc
  291. Example
  292. ~~~~~~~
  293. ::
  294. $conf = array('error_prepend' => '<font color="#ff0000"><tt>',
  295. 'error_append' => '</tt></font>');
  296. $logger = &Log::singleton('display', '', '', $conf, PEAR_LOG_DEBUG);
  297. for ($i = 0; $i < 10; $i++) {
  298. $logger->log("Log entry $i");
  299. }
  300. The Error_Log Handler
  301. ---------------------
  302. The Error_Log handler sends log events to PHP's `error_log()`_ function.
  303. Configuration
  304. ~~~~~~~~~~~~~
  305. +-------------------+-----------+---------------+---------------------------+
  306. | Parameter | Type | Default | Description |
  307. +===================+===========+===============+===========================+
  308. | ``destination`` | String | '' `(empty)` | Optional destination value|
  309. | | | | for `error_log()`_. See |
  310. | | | | `Error_Log Types`_ for |
  311. | | | | more details. |
  312. +-------------------+-----------+---------------+---------------------------+
  313. | ``extra_headers`` | String | '' `(empty)` | Additional headers to pass|
  314. | | | | to the `mail()`_ function |
  315. | | | | when the |
  316. | | | | ``PEAR_LOG_TYPE_MAIL`` |
  317. | | | | type is specified. |
  318. +-------------------+-----------+---------------+---------------------------+
  319. | ``lineFormat`` | String | ``%2$s: %4$s``| `Log line format`_ |
  320. | | | | specification. |
  321. +-------------------+-----------+---------------+---------------------------+
  322. | ``timeFormat`` | String | ``%b %d | Time stamp format |
  323. | | | %H:%M:%S`` | (for strftime_). |
  324. +-------------------+-----------+---------------+---------------------------+
  325. Error_Log Types
  326. ~~~~~~~~~~~~~~~
  327. All of the available log types are detailed in the `error_log()`_ section of
  328. the PHP manual. For your convenience, the Log package also defines the
  329. following constants that can be used for the ``$name`` handler construction
  330. parameter.
  331. +---------------------------+-----------------------------------------------+
  332. | Constant | Description |
  333. +===========================+===============================================+
  334. | ``PEAR_LOG_TYPE_SYSTEM`` | Log events are sent to PHP's system logger, |
  335. | | which uses the operating system's logging |
  336. | | mechanism or a file (depending on the value |
  337. | | of the `error_log configuration directive`_). |
  338. +---------------------------+-----------------------------------------------+
  339. | ``PEAR_LOG_TYPE_MAIL`` | Log events are sent via email to the address |
  340. | | specified in the ``destination`` value. |
  341. +---------------------------+-----------------------------------------------+
  342. | ``PEAR_LOG_TYPE_DEBUG`` | Log events are sent through PHP's debugging |
  343. | | connection. This will only work if |
  344. | | `remote debugging`_ has been enabled. The |
  345. | | ``destination`` value is used to specify the |
  346. | | host name or IP address of the target socket. |
  347. +---------------------------+-----------------------------------------------+
  348. | ``PEAR_LOG_TYPE_FILE`` | Log events will be appended to the file named |
  349. | | by the ``destination`` value. |
  350. +---------------------------+-----------------------------------------------+
  351. .. _error_log(): http://www.php.net/error_log
  352. .. _mail(): http://www.php.net/mail
  353. .. _error_log configuration directive: http://www.php.net/errorfunc#ini.error-log
  354. .. _remote debugging: http://www.php.net/install.configure#install.configure.enable-debugger
  355. Example
  356. ~~~~~~~
  357. ::
  358. $logger = &Log::singleton('error_log', PEAR_LOG_TYPE_SYSTEM, 'ident');
  359. for ($i = 0; $i < 10; $i++) {
  360. $logger->log("Log entry $i");
  361. }
  362. The File Handler
  363. ----------------
  364. The File handler writes log events to a text file using configurable string
  365. formats.
  366. Configuration
  367. ~~~~~~~~~~~~~
  368. +-------------------+-----------+---------------+---------------------------+
  369. | Parameter | Type | Default | Description |
  370. +===================+===========+===============+===========================+
  371. | ``append`` | Boolean | True | Should new log entries be |
  372. | | | | append to an existing log |
  373. | | | | file, or should the a new |
  374. | | | | log file overwrite an |
  375. | | | | existing one? |
  376. +-------------------+-----------+---------------+---------------------------+
  377. | ``locking`` | Boolean | False | Should advisory file |
  378. | | | | locking (using flock_) be |
  379. | | | | used? |
  380. +-------------------+-----------+---------------+---------------------------+
  381. | ``mode`` | Integer | 0644 | Octal representation of |
  382. | | | | the log file's permissions|
  383. | | | | mode. |
  384. +-------------------+-----------+---------------+---------------------------+
  385. | ``dirmode`` | Integer | 0755 | Octal representation of |
  386. | | | | the file permission mode |
  387. | | | | that will be used when |
  388. | | | | creating directories that |
  389. | | | | do not already exist. |
  390. +-------------------+-----------+---------------+---------------------------+
  391. | ``eol`` | String | OS default | The end-on-line character |
  392. | | | | sequence. |
  393. +-------------------+-----------+---------------+---------------------------+
  394. | ``lineFormat`` | String | ``%1$s %2$s | `Log line format`_ |
  395. | | | [%3$s] %4$s`` | specification. |
  396. +-------------------+-----------+---------------+---------------------------+
  397. | ``timeFormat`` | String | ``%b %d | Time stamp format |
  398. | | | %H:%M:%S`` | (for strftime_). |
  399. +-------------------+-----------+---------------+---------------------------+
  400. .. _flock: http://www.php.net/flock
  401. .. _strftime: http://www.php.net/strftime
  402. The file handler will only attempt to set the ``mode`` value if it was
  403. responsible for creating the file.
  404. Example
  405. ~~~~~~~
  406. ::
  407. $conf = array('mode' => 0600, 'timeFormat' => '%X %x');
  408. $logger = &Log::singleton('file', 'out.log', 'ident', $conf);
  409. for ($i = 0; $i < 10; $i++) {
  410. $logger->log("Log entry $i");
  411. }
  412. The Firebug Handler
  413. -------------------
  414. The Firebug handler outputs log events to the Firebug_ console. It supports
  415. output buffering and configurable string formats.
  416. Configuration
  417. ~~~~~~~~~~~~~
  418. +-------------------+-----------+---------------+---------------------------+
  419. | Parameter | Type | Default | Description |
  420. +===================+===========+===============+===========================+
  421. | ``buffering`` | Boolean | False | Should the output be |
  422. | | | | buffered until shutdown? |
  423. +-------------------+-----------+---------------+---------------------------+
  424. | ``lineFormat`` | String | ``%2$s [%3$s] | `Log line format`_ |
  425. | | | %4$s`` | specification. |
  426. +-------------------+-----------+---------------+---------------------------+
  427. | ``timeFormat`` | String | ``%b %d | Time stamp format |
  428. | | | %H:%M:%S`` | (for strftime_). |
  429. +-------------------+-----------+---------------+---------------------------+
  430. .. _Firebug: http://www.getfirebug.com/
  431. .. _strftime: http://www.php.net/strftime
  432. Example
  433. ~~~~~~~
  434. ::
  435. $logger = &Log::singleton('firebug', '', 'ident');
  436. for ($i = 0; $i < 10; $i++) {
  437. $logger->log("Log entry $i");
  438. }
  439. The Mail Handler
  440. ----------------
  441. The Mail handler aggregates a session's log events and sends them in the body
  442. of an email message using either the `PEAR Mail`_ package or PHP's native
  443. `mail()`_ function.
  444. If an empty ``mailBackend`` value is specified, the `mail()`_ function will be
  445. used instead of the `PEAR Mail`_ package.
  446. Multiple recipients can be specified by separating their email addresses with
  447. commas in the ``$name`` construction parameter.
  448. Configuration
  449. ~~~~~~~~~~~~~
  450. +-------------------+-----------+---------------+---------------------------+
  451. | Parameter | Type | Default | Description |
  452. +===================+===========+===============+===========================+
  453. | ``from`` | String | sendmail_from | Value for the message's |
  454. | | | INI value | ``From:`` header. |
  455. +-------------------+-----------+---------------+---------------------------+
  456. | ``subject`` | String | ``[Log_mail] | Value for the message's |
  457. | | | Log message`` | ``Subject:`` header. |
  458. +-------------------+-----------+---------------+---------------------------+
  459. | ``preamble`` | String | `` `(empty)` | Preamble for the message. |
  460. +-------------------+-----------+---------------+---------------------------+
  461. | ``lineFormat`` | String | ``%1$s %2$s | `Log line format`_ |
  462. | | | [%3$s] %4$s`` | specification. |
  463. +-------------------+-----------+---------------+---------------------------+
  464. | ``timeFormat`` | String | ``%b %d | Time stamp format |
  465. | | | %H:%M:%S`` | (for strftime_). |
  466. +-------------------+-----------+---------------+---------------------------+
  467. | ``mailBackend`` | String | `` `(empty)` | Name of the Mail package |
  468. | | | | backend to use. |
  469. +-------------------+-----------+---------------+---------------------------+
  470. | ``mailParams`` | Array | `(empty)` | Array of parameters that |
  471. | | | | will be passed to the |
  472. | | | | Mail package backend. |
  473. +-------------------+-----------+---------------+---------------------------+
  474. .. _PEAR Mail: http://pear.php.net/package/Mail
  475. .. _mail(): http://www.php.net/mail
  476. Example
  477. ~~~~~~~
  478. ::
  479. $conf = array('subject' => 'Important Log Events');
  480. $logger = &Log::singleton('mail', 'webmaster@example.com', 'ident', $conf);
  481. for ($i = 0; $i < 10; $i++) {
  482. $logger->log("Log entry $i");
  483. }
  484. The MDB2 Handler
  485. ----------------
  486. The MDB2 handler is similar to `the SQL (DB) handler`_, but instead of using
  487. the PEAR DB package, it uses the `MDB2 database abstraction package`_.
  488. Configuration
  489. ~~~~~~~~~~~~~
  490. +-------------------+-----------+---------------+---------------------------+
  491. | Parameter | Type | Default | Description |
  492. +===================+===========+===============+===========================+
  493. | ``dsn`` | Mixed | '' `(empty)` | A `Data Source Name`_. |
  494. | | | | |required| |
  495. +-------------------+-----------+---------------+---------------------------+
  496. | ``options`` | Array | ``persistent``| An array of `MDB2`_ |
  497. | | | | options. |
  498. +-------------------+-----------+---------------+---------------------------+
  499. | ``db`` | Object | NULL | An existing `MDB2`_ |
  500. | | | | object. If specified, |
  501. | | | | this object will be used, |
  502. | | | | and ``dsn`` will be |
  503. | | | | ignored. |
  504. +-------------------+-----------+---------------+---------------------------+
  505. | ``sequence`` | String | ``log_id`` | The name of the sequence |
  506. | | | | to use when generating |
  507. | | | | unique event IDs. Under |
  508. | | | | many databases, this will |
  509. | | | | be used as the name of |
  510. | | | | the sequence table. |
  511. +-------------------+-----------+---------------+---------------------------+
  512. | ``identLimit`` | Integer | 16 | The maximum length of the |
  513. | | | | ``ident`` string. |
  514. | | | | **Changing this value may |
  515. | | | | require updates to the SQL|
  516. | | | | schema, as well.** |
  517. +-------------------+-----------+---------------+---------------------------+
  518. | ``singleton`` | Boolean | false | Is true, use a singleton |
  519. | | | | database object using |
  520. | | | | `MDB2::singleton()`_. |
  521. +-------------------+-----------+---------------+---------------------------+
  522. .. _MDB2: http://pear.php.net/package/MDB2
  523. .. _MDB2 database abstraction package: MDB2_
  524. .. _MDB2::singleton(): http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2.html#methodsingleton
  525. The Null Handler
  526. ----------------
  527. The Null handler simply consumes log events (akin to sending them to
  528. ``/dev/null``). `Log level masks`_ are respected, and the event will still be
  529. sent to any registered `log observers`_.
  530. Example
  531. ~~~~~~~
  532. ::
  533. $logger = &Log::singleton('null');
  534. for ($i = 0; $i < 10; $i++) {
  535. $logger->log("Log entry $i");
  536. }
  537. The SQL (DB) Handler
  538. --------------------
  539. The SQL handler sends log events to a database using `PEAR's DB abstraction
  540. layer`_.
  541. **Note:** Due to the constraints of the default database schema, the SQL
  542. handler limits the length of the ``$ident`` string to sixteen (16) characters.
  543. This limit can be adjusted using the ``identLimit`` configuration parameter.
  544. The Log Table
  545. ~~~~~~~~~~~~~
  546. The default SQL table used by this handler looks like this::
  547. CREATE TABLE log_table (
  548. id INT NOT NULL,
  549. logtime TIMESTAMP NOT NULL,
  550. ident CHAR(16) NOT NULL,
  551. priority INT NOT NULL,
  552. message VARCHAR(200),
  553. PRIMARY KEY (id)
  554. );
  555. This is the "lowest common denominator" that should work across all SQL
  556. compliant database. You may want to make database- or site-specific changes
  557. to this schema to support your specific needs, however. For example,
  558. `PostgreSQL`_ users may prefer to use a ``TEXT`` type for the ``message``
  559. field.
  560. .. _PostgreSQL: http://www.postgresql.org/
  561. Configuration
  562. ~~~~~~~~~~~~~
  563. +-------------------+-----------+---------------+---------------------------+
  564. | Parameter | Type | Default | Description |
  565. +===================+===========+===============+===========================+
  566. | ``dsn`` | Mixed | '' `(empty)` | A `Data Source Name`_. |
  567. | | | | |required| |
  568. +-------------------+-----------+---------------+---------------------------+
  569. | ``sql`` | String | |sql-default| | SQL insertion statement. |
  570. +-------------------+-----------+---------------+---------------------------+
  571. | ``options`` | Array | ``persistent``| An array of `DB`_ options.|
  572. +-------------------+-----------+---------------+---------------------------+
  573. | ``db`` | Object | NULL | An existing `DB`_ object. |
  574. | | | | If specified, this object |
  575. | | | | will be used, and ``dsn`` |
  576. | | | | will be ignored. |
  577. +-------------------+-----------+---------------+---------------------------+
  578. | ``sequence`` | String | ``log_id`` | The name of the sequence |
  579. | | | | to use when generating |
  580. | | | | unique event IDs. Under |
  581. | | | | many databases, this will |
  582. | | | | be used as the name of |
  583. | | | | the sequence table. |
  584. +-------------------+-----------+---------------+---------------------------+
  585. | ``identLimit`` | Integer | 16 | The maximum length of the |
  586. | | | | ``ident`` string. |
  587. | | | | **Changing this value may |
  588. | | | | require updates to the SQL|
  589. | | | | schema, as well.** |
  590. +-------------------+-----------+---------------+---------------------------+
  591. The name of the database table to which the log entries will be written is
  592. specified using the ``$name`` construction parameter (see `Configuring a
  593. Handler`_).
  594. .. |sql-default| replace:: ``INSERT INTO $table (id, logtime, ident, priority, message) VALUES(?, CURRENT_TIMESTAMP, ?, ?, ?)``
  595. .. _DB: http://pear.php.net/package/DB
  596. .. _PEAR's DB abstraction layer: DB_
  597. .. _Data Source Name: http://pear.php.net/manual/en/package.database.db.intro-dsn.php
  598. Examples
  599. ~~~~~~~~
  600. Using a `Data Source Name`_ to create a new database connection::
  601. $conf = array('dsn' => 'pgsql://jon@localhost+unix/logs');
  602. $logger = &Log::singleton('sql', 'log_table', 'ident', $conf);
  603. for ($i = 0; $i < 10; $i++) {
  604. $logger->log("Log entry $i");
  605. }
  606. Using an existing `DB`_ object::
  607. require_once 'DB.php';
  608. $db = &DB::connect('pgsql://jon@localhost+unix/logs');
  609. $conf['db'] = $db;
  610. $logger = &Log::singleton('sql', 'log_table', 'ident', $conf);
  611. for ($i = 0; $i < 10; $i++) {
  612. $logger->log("Log entry $i");
  613. }
  614. The Sqlite Handler
  615. ------------------
  616. :Author: Bertrand Mansion
  617. The Sqlite handler sends log events to an Sqlite database using the `native
  618. PHP sqlite functions`_.
  619. It is faster than `the SQL (DB) handler`_ because requests are made directly
  620. to the database without using an abstraction layer. It is also interesting to
  621. note that Sqlite database files can be moved, copied, and deleted on your
  622. system just like any other files, which makes log management easier. Last but
  623. not least, using a database to log your events allows you to use SQL queries
  624. to create reports and statistics.
  625. When using a database and logging a lot of events, it is recommended to split
  626. the database into smaller databases. This is allowed by Sqlite, and you can
  627. later use the Sqlite `ATTACH`_ statement to query your log database files
  628. globally.
  629. If the database does not exist when the log is opened, sqlite will try to
  630. create it automatically. If the log table does not exist, it will also be
  631. automatically created. The table creation uses the following SQL request::
  632. CREATE TABLE log_table (
  633. id INTEGER PRIMARY KEY NOT NULL,
  634. logtime NOT NULL,
  635. ident CHAR(16) NOT NULL,
  636. priority INT NOT NULL,
  637. message
  638. );
  639. Configuration
  640. ~~~~~~~~~~~~~
  641. +-------------------+-----------+---------------+---------------------------+
  642. | Parameter | Type | Default | Description |
  643. +===================+===========+===============+===========================+
  644. | ``filename`` | String | '' `(empty)` | Path to an Sqlite |
  645. | | | | database. |required| |
  646. +-------------------+-----------+---------------+---------------------------+
  647. | ``mode`` | Integer | 0666 | Octal mode used to open |
  648. | | | | the database. |
  649. +-------------------+-----------+---------------+---------------------------+
  650. | ``persistent`` | Boolean | false | Use a persistent |
  651. | | | | connection. |
  652. +-------------------+-----------+---------------+---------------------------+
  653. An already opened database connection can also be passed as parameter instead
  654. of the above configuration. In this case, closing the database connection is
  655. up to the user.
  656. .. _native PHP sqlite functions: http://www.php.net/sqlite
  657. .. _ATTACH: http://www.sqlite.org/lang.html#attach
  658. Examples
  659. ~~~~~~~~
  660. Using a configuration to create a new database connection::
  661. $conf = array('filename' => 'log.db', 'mode' => 0666, 'persistent' => true);
  662. $logger =& Log::factory('sqlite', 'log_table', 'ident', $conf);
  663. $logger->log('logging an event', PEAR_LOG_WARNING);
  664. Using an existing connection::
  665. $db = sqlite_open('log.db', 0666, $error);
  666. $logger =& Log::factory('sqlite', 'log_table', 'ident', $db);
  667. $logger->log('logging an event', PEAR_LOG_WARNING);
  668. sqlite_close($db);
  669. The Syslog Handler
  670. ------------------
  671. The Syslog handler sends log events to the system logging service (syslog on
  672. Unix-like environments or the Event Log on Windows systems). The events are
  673. sent using PHP's `syslog()`_ function.
  674. Configuration
  675. ~~~~~~~~~~~~~
  676. +-------------------+-----------+---------------+---------------------------+
  677. | Parameter | Type | Default | Description |
  678. +===================+===========+===============+===========================+
  679. | ``inherit`` | Boolean | false | Inherit the current syslog|
  680. | | | | connection for this |
  681. | | | | process, or start a new |
  682. | | | | one via `openlog()`_? |
  683. +-------------------+-----------+---------------+---------------------------+
  684. Facilities
  685. ~~~~~~~~~~
  686. +-------------------+-------------------------------------------------------+
  687. | Constant | Category Description |
  688. +===================+=======================================================+
  689. | ``LOG_AUTH`` | Security / authorization messages; ``LOG_AUTHPRIV`` is|
  690. | | preferred on systems where it is defined. |
  691. +-------------------+-------------------------------------------------------+
  692. | ``LOG_AUTHPRIV`` | Private security / authorization messages |
  693. +-------------------+-------------------------------------------------------+
  694. | ``LOG_CRON`` | Clock daemon (``cron`` and ``at``) |
  695. +-------------------+-------------------------------------------------------+
  696. | ``LOG_DAEMON`` | System daemon processes |
  697. +-------------------+-------------------------------------------------------+
  698. | ``LOG_KERN`` | Kernel messages |
  699. +-------------------+-------------------------------------------------------+
  700. | ``LOG_LOCAL0`` .. | Reserved for local use; **not** available under |
  701. | ``LOG_LOCAL7`` | Windows. |
  702. +-------------------+-------------------------------------------------------+
  703. | ``LOG_LPR`` | Printer subsystem |
  704. +-------------------+-------------------------------------------------------+
  705. | ``LOG_MAIL`` | Mail subsystem |
  706. +-------------------+-------------------------------------------------------+
  707. | ``LOG_NEWS`` | USENET news subsystem |
  708. +-------------------+-------------------------------------------------------+
  709. | ``LOG_SYSLOG`` | Internal syslog messages |
  710. +-------------------+-------------------------------------------------------+
  711. | ``LOG_USER`` | Generic user-level messages |
  712. +-------------------+-------------------------------------------------------+
  713. | ``LOG_UUCP`` | UUCP subsystem |
  714. +-------------------+-------------------------------------------------------+
  715. .. _syslog(): http://www.php.net/syslog
  716. .. _openlog(): http://www.php.net/openlog
  717. Example
  718. ~~~~~~~
  719. ::
  720. $logger = &Log::singleton('syslog', LOG_LOCAL0, 'ident');
  721. for ($i = 0; $i < 10; $i++) {
  722. $logger->log("Log entry $i");
  723. }
  724. The Window Handler
  725. ------------------
  726. The Window handler sends log events to a separate browser window. The
  727. original idea for this handler was inspired by Craig Davis' Zend.com article
  728. entitled `"JavaScript Power PHP Debugging"`_.
  729. Configuration
  730. ~~~~~~~~~~~~~
  731. +-------------------+-----------+---------------+---------------------------+
  732. | Parameter | Type | Default | Description |
  733. +===================+===========+===============+===========================+
  734. | ``title`` | String | ``Log Output | The title of the output |
  735. | | | Window`` | window. |
  736. +-------------------+-----------+---------------+---------------------------+
  737. | ``styles`` | Array | `ROY G BIV`_ | Mapping of log priorities |
  738. | | | (high to low) | to CSS styles. |
  739. +-------------------+-----------+---------------+---------------------------+
  740. **Note:** The Window handler may not work reliably when PHP's `output
  741. buffering`_ system is enabled.
  742. .. _"JavaScript Power PHP Debugging": http://www.zend.com/zend/tut/tutorial-DebugLib.php
  743. .. _ROY G BIV: http://www.cis.rit.edu/
  744. .. _output buffering: http://www.php.net/outcontrol
  745. Example
  746. ~~~~~~~
  747. ::
  748. $conf = array('title' => 'Sample Log Output');
  749. $logger = &Log::singleton('win', 'LogWindow', 'ident', $conf);
  750. for ($i = 0; $i < 10; $i++) {
  751. $logger->log("Log entry $i");
  752. }
  753. Composite Handlers
  754. ==================
  755. It is often useful to log events to multiple handlers. The Log package
  756. provides a compositing system that marks this task trivial.
  757. Start by creating the individual log handlers::
  758. $console = &Log::singleton('console', '', 'TEST');
  759. $file = &Log::singleton('file', 'out.log', 'TEST');
  760. Then, construct a composite handler and add the individual handlers as
  761. children of the composite::
  762. $composite = &Log::singleton('composite');
  763. $composite->addChild($console);
  764. $composite->addChild($file);
  765. The composite handler implements the standard ``Log`` interface so you can use
  766. it just like any of the other handlers::
  767. $composite->log('This event will be logged to both handlers.');
  768. Children can be removed from the composite when they're not longer needed::
  769. $composite->removeChild($file);
  770. Log Observers
  771. =============
  772. Log observers provide an implementation of the `observer pattern`_. In the
  773. content of the Log package, they provide a mechanism by which you can examine
  774. (i.e. observe) each event as it is logged. This allows the implementation of
  775. special behavior based on the contents of a log event. For example, the
  776. observer code could send an alert email if a log event contained the string
  777. ``PANIC``.
  778. Creating a log observer involves implementing a subclass of the
  779. ``Log_observer`` class. The subclass must override the base class's
  780. ``notify()`` method. This method is passed a hash containing the event's
  781. priority and event. The subclass's implementation is free to act upon this
  782. information in any way it likes.
  783. Log observers are attached to ``Log`` instances via the ``attach()`` method::
  784. $observer = &Log_observer::factory('yourType');
  785. $logger->attach($observer);
  786. Observers can be detached using the ``detach()`` method::
  787. $logger->detach($observer);
  788. At this time, no concrete ``Log_observer`` implementations are distributed
  789. with the Log package.
  790. .. _observer pattern: http://wikipedia.org/wiki/Observer_pattern
  791. Logging From Standard Error Handlers
  792. ====================================
  793. Logging PHP Errors
  794. ------------------
  795. PHP's default error handler can be overridden using the `set_error_handler()`_
  796. function. The custom error handling function can use a global Log instance to
  797. log the PHP errors.
  798. **Note:** Fatal PHP errors cannot be handled by a custom error handler at this
  799. time.
  800. ::
  801. function errorHandler($code, $message, $file, $line)
  802. {
  803. global $logger;
  804. /* Map the PHP error to a Log priority. */
  805. switch ($code) {
  806. case E_WARNING:
  807. case E_USER_WARNING:
  808. $priority = PEAR_LOG_WARNING;
  809. break;
  810. case E_NOTICE:
  811. case E_USER_NOTICE:
  812. $priority = PEAR_LOG_NOTICE;
  813. break;
  814. case E_ERROR:
  815. case E_USER_ERROR:
  816. $priority = PEAR_LOG_ERR;
  817. break;
  818. default:
  819. $priority = PEAR_LOG_INFO;
  820. }
  821. $logger->log($message . ' in ' . $file . ' at line ' . $line,
  822. $priority);
  823. }
  824. set_error_handler('errorHandler');
  825. trigger_error('This is an information log message.', E_USER_NOTICE);
  826. .. _set_error_handler(): http://www.php.net/set_error_handler
  827. Logging PHP Assertions
  828. ----------------------
  829. PHP allows user-defined `assert()`_ callback handlers. The assertion callback
  830. is configured using the `assert_options()`_ function.
  831. ::
  832. function assertCallback($file, $line, $message)
  833. {
  834. global $logger;
  835. $logger->log($message . ' in ' . $file . ' at line ' . $line,
  836. PEAR_LOG_ALERT);
  837. }
  838. assert_options(ASSERT_CALLBACK, 'assertCallback');
  839. assert(false);
  840. .. _assert(): http://www.php.net/assert
  841. .. _assert_options(): http://www.php.net/assert_options
  842. Logging PHP Exceptions
  843. ----------------------
  844. PHP 5 and later support the concept of `exceptions`_. A custom exception
  845. handler can be assigned using the `set_exception_handler()`_ function.
  846. ::
  847. function exceptionHandler($exception)
  848. {
  849. global $logger;
  850. $logger->log($exception->getMessage(), PEAR_LOG_ALERT);
  851. }
  852. set_exception_handler('exceptionHandler');
  853. throw new Exception('Uncaught Exception');
  854. .. _exceptions: http://www.php.net/exceptions
  855. .. _set_exception_handler(): http://www.php.net/set_exception_handler
  856. Logging PEAR Errors
  857. -------------------
  858. The Log package can be used with `PEAR::setErrorHandling()`_'s
  859. ``PEAR_ERROR_CALLBACK`` mechanism by writing an error handling function that
  860. uses a global Log instance. Here's an example::
  861. function errorHandler($error)
  862. {
  863. global $logger;
  864. $message = $error->getMessage();
  865. if (!empty($error->backtrace[1]['file'])) {
  866. $message .= ' (' . $error->backtrace[1]['file'];
  867. if (!empty($error->backtrace[1]['line'])) {
  868. $message .= ' at line ' . $error->backtrace[1]['line'];
  869. }
  870. $message .= ')';
  871. }
  872. $logger->log($message, $error->code);
  873. }
  874. PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'errorHandler');
  875. PEAR::raiseError('This is an information log message.', PEAR_LOG_INFO);
  876. .. _PEAR::setErrorHandling(): http://pear.php.net/manual/en/core.pear.pear.seterrorhandling.php
  877. Custom Handlers
  878. ===============
  879. There are times when the standard handlers aren't a perfect match for your
  880. needs. In those situations, the solution might be to write a custom handler.
  881. Using a Custom Handler
  882. ----------------------
  883. Using a custom Log handler is very simple. Once written (see `Writing New
  884. Handlers`_ and `Extending Existing Handlers`_ below), you have the choice of
  885. placing the file in your PEAR installation's main ``Log/`` directory (usually
  886. something like ``/usr/local/lib/php/Log`` or ``C:\php\pear\Log``), where it
  887. can be found and use by any PHP application on the system, or placing the file
  888. somewhere in your application's local hierarchy and including it before the
  889. the custom Log object is constructed.
  890. Method 1: Handler in the Standard Location
  891. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  892. After copying the handler file to your PEAR installation's ``Log/`` directory,
  893. simply treat the handler as if it were part of the standard distributed. If
  894. your handler is named ``custom`` (and therefore implemented by a class named
  895. ``Log_custom``)::
  896. require_once 'Log.php';
  897. $logger = &Log::factory('custom', '', 'CUSTOM');
  898. Method 2: Handler in a Custom Location
  899. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  900. If you prefer storing your handler in your application's local hierarchy,
  901. you'll need to include that file before you can create a Log instance based on
  902. it.
  903. ::
  904. require_once 'Log.php';
  905. require_once 'LocalHandlers/custom.php';
  906. $logger = &Log::factory('custom', '', 'CUSTOM');
  907. Writing New Handlers
  908. --------------------
  909. Writing a new …

Large files files are truncated, but you can click here to view the full file