guide.txt 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. =================
  2. The Log Package
  3. =================
  4. --------------------
  5. User Documentation
  6. --------------------
  7. :Author: Jon Parise
  8. :Contact: jon@php.net
  9. :Date: $Date: 2004/01/31 21:48:16 $
  10. :Revision: $Revision: 1.10 $
  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 a certain level, use the
  164. ``Log::UPTO()`` method::
  165. $mask = Log::UPTO(PEAR_LOG_INFO);
  166. The apply the mask, use the ``setMask()`` method::
  167. $logger->setMask($mask);
  168. Masks can be be combined using bitwise operations. To restrict logging to
  169. only those events marked as ``PEAR_LOG_NOTICE`` or ``PEAR_LOG_DEBUG``::
  170. $mask = Log::MASK(PEAR_LOG_NOTICE) | Log::MASK(PEAR_LOG_DEBUG);
  171. $logger->setMask($mask);
  172. For convenience, two special masks are predefined: ``PEAR_LOG_NONE`` and
  173. ``PEAR_LOG_ALL``. ``PEAR_LOG_ALL`` is especially useful for exluding only
  174. specific priorities::
  175. $mask = PEAR_LOG_ALL ^ Log::MASK(PEAR_LOG_NOTICE);
  176. $logger->setMask($mask);
  177. It is also possible to retrieve and modify a Log object's existing mask::
  178. $mask = $logger->getMask() | Log::MASK(PEAR_LOG_INFO);
  179. $logger->setMask($mask);
  180. Flushing Log Events
  181. -------------------
  182. Some log handlers (such as `the console handler`_) support explicit
  183. "buffering". When buffering is enabled, log events won't actually be written
  184. to the output stream until the handler is closed. Other handlers (such as
  185. `the file handler`_) support implicit buffering because they use the operating
  186. system's IO routines, which may buffer the output.
  187. It's possible to force these handlers to flush their output, however, by
  188. calling their ``flush()`` method::
  189. $conf = array('buffering' => true);
  190. $logger = &Log::singleton('console', '', 'test', $conf);
  191. for ($i = 0; $i < 10; $i++) {
  192. $logger->log('This event will be buffered.');
  193. }
  194. /* Flush all of the buffered log events. */
  195. $logger->flush();
  196. for ($i = 0; $i < 10; $i++) {
  197. $logger->log('This event will be buffered.');
  198. }
  199. /* Implicitly flush the buffered events on close. */
  200. $logger->close();
  201. At this time, the ``flush()`` method is only implemented by `the console
  202. handler`_, `the file handler`_ and `the mail handler`_.
  203. Standard Log Handlers
  204. =====================
  205. The Console Handler
  206. -------------------
  207. The Console handler outputs log events directly to the console. It supports
  208. output buffering and configurable string formats.
  209. Configuration
  210. ~~~~~~~~~~~~~
  211. +-------------------+-----------+---------------+---------------------------+
  212. | Parameter | Type | Default | Description |
  213. +===================+===========+===============+===========================+
  214. | ``stream`` | File | STDOUT_ | The output stream to use. |
  215. +-------------------+-----------+---------------+---------------------------+
  216. | ``buffering`` | Boolean | False | Should the output be |
  217. | | | | buffered until shutdown? |
  218. +-------------------+-----------+---------------+---------------------------+
  219. | ``lineFormat`` | String | ``%1$s %2$s | Log line format |
  220. | | | [%3$s] %4$s`` | specification. |
  221. +-------------------+-----------+---------------+---------------------------+
  222. | ``timeFormat`` | String | ``%b %d | Time stamp format |
  223. | | | %H:%M:%S`` | (for strftime_). |
  224. +-------------------+-----------+---------------+---------------------------+
  225. .. _STDOUT: http://www.php.net/wrappers.php
  226. .. _strftime: http://www.php.net/strftime
  227. Example
  228. ~~~~~~~
  229. ::
  230. $logger = &Log::singleton('console', '', 'ident');
  231. for ($i = 0; $i < 10; $i++) {
  232. $logger->log("Log entry $i");
  233. }
  234. The Display Handler
  235. -------------------
  236. The Display handler simply prints the log events back to the browser. It
  237. respects the ``error_prepend_string`` and ``error_append_string`` `error
  238. handling values`_ and is useful when `logging from standard error handlers`_.
  239. Configuration
  240. ~~~~~~~~~~~~~
  241. +-------------------+-----------+---------------+---------------------------+
  242. | Parameter | Type | Default | Description |
  243. +===================+===========+===============+===========================+
  244. | ``error_prepend`` | String | PHP INI value | This string will be |
  245. | | | | prepended to the log |
  246. | | | | output. |
  247. +-------------------+-----------+---------------+---------------------------+
  248. | ``error_append`` | String | PHP INI value | This string will be |
  249. | | | | appended to the log |
  250. | | | | output. |
  251. +-------------------+-----------+---------------+---------------------------+
  252. .. _error handling values: http://www.php.net/errorfunc
  253. Example
  254. ~~~~~~~
  255. ::
  256. $conf = array('error_prepend' => '<font color="#ff0000"><tt>',
  257. 'error_append' => '</tt></font>');
  258. $logger = &Log::singleton('display', '', '', $conf, PEAR_LOG_DEBUG);
  259. for ($i = 0; $i < 10; $i++) {
  260. $logger->log("Log entry $i");
  261. }
  262. The Error_Log Handler
  263. ---------------------
  264. The Error_Log handler sends log events to PHP's `error_log()`_ function.
  265. Configuration
  266. ~~~~~~~~~~~~~
  267. +-------------------+-----------+---------------+---------------------------+
  268. | Parameter | Type | Default | Description |
  269. +===================+===========+===============+===========================+
  270. | ``destination`` | String | '' `(empty)` | Optional destination value|
  271. | | | | for `error_log()`_. See |
  272. | | | | `Error_Log Types`_ for |
  273. | | | | more details. |
  274. +-------------------+-----------+---------------+---------------------------+
  275. | ``extra_headers`` | String | '' `(empty)` | Additional headers to pass|
  276. | | | | to the `mail()`_ function |
  277. | | | | when the |
  278. | | | | ``PEAR_LOG_TYPE_MAIL`` |
  279. | | | | type is specified. |
  280. +-------------------+-----------+---------------+---------------------------+
  281. Error_Log Types
  282. ~~~~~~~~~~~~~~~
  283. All of the available log types are detailed in the `error_log()`_ section of
  284. the PHP manual. For your convenience, the Log package also defines the
  285. following constants that can be used for the ``$name`` handler construction
  286. parameter.
  287. +---------------------------+-----------------------------------------------+
  288. | Constant | Description |
  289. +===========================+===============================================+
  290. | ``PEAR_LOG_TYPE_SYSTEM`` | Log events are sent to PHP's system logger, |
  291. | | which uses the operating system's logging |
  292. | | mechanism or a file (depending on the value |
  293. | | of the `error_log configuration directive`_). |
  294. +---------------------------+-----------------------------------------------+
  295. | ``PEAR_LOG_TYPE_MAIL`` | Log events are sent via email to the address |
  296. | | specified in the ``destination`` value. |
  297. +---------------------------+-----------------------------------------------+
  298. | ``PEAR_LOG_TYPE_DEBUG`` | Log events are sent through PHP's debugging |
  299. | | connection. This will only work if |
  300. | | `remote debugging`_ has been enabled. The |
  301. | | ``destination`` value is used to specify the |
  302. | | host name or IP address of the target socket. |
  303. +---------------------------+-----------------------------------------------+
  304. | ``PEAR_LOG_TYPE_FILE`` | Log events will be appended to the file named |
  305. | | by the ``destination`` value. |
  306. +---------------------------+-----------------------------------------------+
  307. .. _error_log(): http://www.php.net/error_log
  308. .. _mail(): http://www.php.net/mail
  309. .. _error_log configuration directive: http://www.php.net/errorfunc#ini.error-log
  310. .. _remote debugging: http://www.php.net/install.configure#install.configure.enable-debugger
  311. Example
  312. ~~~~~~~
  313. ::
  314. $logger = &Log::singleton('error_log', PEAR_LOG_TYPE_SYSTEM, 'ident');
  315. for ($i = 0; $i < 10; $i++) {
  316. $logger->log("Log entry $i");
  317. }
  318. The File Handler
  319. ----------------
  320. The File handler writes log events to a text file using configurable string
  321. formats.
  322. Configuration
  323. ~~~~~~~~~~~~~
  324. +-------------------+-----------+---------------+---------------------------+
  325. | Parameter | Type | Default | Description |
  326. +===================+===========+===============+===========================+
  327. | ``append`` | Boolean | True | Should new log entries be |
  328. | | | | append to an existing log |
  329. | | | | file, or should the a new |
  330. | | | | log file overwrite an |
  331. | | | | existing one? |
  332. +-------------------+-----------+---------------+---------------------------+
  333. | ``mode`` | Integer | 0644 | Octal representation of |
  334. | | | | the log file's permissions|
  335. | | | | mode. |
  336. +-------------------+-----------+---------------+---------------------------+
  337. | ``eol`` | String | OS default | The end-on-line character |
  338. | | | | sequence. |
  339. +-------------------+-----------+---------------+---------------------------+
  340. | ``lineFormat`` | String | ``%1$s %2$s | Log line format |
  341. | | | [%3$s] %4$s`` | specification. |
  342. +-------------------+-----------+---------------+---------------------------+
  343. | ``timeFormat`` | String | ``%b %d | Time stamp format |
  344. | | | %H:%M:%S`` | (for strftime_). |
  345. +-------------------+-----------+---------------+---------------------------+
  346. .. _strftime: http://www.php.net/strftime
  347. Example
  348. ~~~~~~~
  349. ::
  350. $conf = array('mode' => 0600, 'timeFormat' => '%X %x');
  351. $logger = &Log::singleton('file', 'out.log', 'ident', $conf);
  352. for ($i = 0; $i < 10; $i++) {
  353. $logger->log("Log entry $i");
  354. }
  355. The Mail Handler
  356. ----------------
  357. The Mail handler aggregates a session's log events and sends them in the body
  358. of an email message using PHP's `mail()`_ function.
  359. Configuration
  360. ~~~~~~~~~~~~~
  361. +-------------------+-----------+---------------+---------------------------+
  362. | Parameter | Type | Default | Description |
  363. +===================+===========+===============+===========================+
  364. | ``from`` | String | sendmail_from | Value for the message's |
  365. | | | INI value | ``From:`` header. |
  366. +-------------------+-----------+---------------+---------------------------+
  367. | ``subject`` | String | ``[Log_mail] | Value for the message's |
  368. | | | Log message`` | ``Subject:`` header. |
  369. +-------------------+-----------+---------------+---------------------------+
  370. | ``preamble`` | String | `` `(empty)` | Preamble for the message. |
  371. +-------------------+-----------+---------------+---------------------------+
  372. .. _mail(): http://www.php.net/mail
  373. Example
  374. ~~~~~~~
  375. ::
  376. $conf = array('subject' => 'Important Log Events');
  377. $logger = &Log::singleton('mail', 'webmaster@example.com', 'ident', $conf);
  378. for ($i = 0; $i < 10; $i++) {
  379. $logger->log("Log entry $i");
  380. }
  381. The Null Handler
  382. ----------------
  383. The Null handler simply consumes log events (akin to sending them to
  384. ``/dev/null``). `Log level masks`_ are respected, and the event will still be
  385. sent to any registered `log observers`_.
  386. Example
  387. ~~~~~~~
  388. ::
  389. $logger = &Log::singleton('null');
  390. for ($i = 0; $i < 10; $i++) {
  391. $logger->log("Log entry $i");
  392. }
  393. The SQL (DB) Handler
  394. --------------------
  395. The SQL handler sends log events to a database using `PEAR's DB abstraction
  396. layer`_.
  397. Configuration
  398. ~~~~~~~~~~~~~
  399. +-------------------+-----------+---------------+---------------------------+
  400. | Parameter | Type | Default | Description |
  401. +===================+===========+===============+===========================+
  402. | ``dsn`` | String | '' `(empty)` | A `Data Source Name`_. |
  403. | | | | |required| |
  404. +-------------------+-----------+---------------+---------------------------+
  405. | ``db`` | Object | NULL | An existing `DB`_ object. |
  406. | | | | If specified, this object |
  407. | | | | will be used, and ``dsn`` |
  408. | | | | will be ignored. |
  409. +-------------------+-----------+---------------+---------------------------+
  410. .. _DB: http://pear.php.net/package/DB
  411. .. _PEAR's DB abstraction layer: DB_
  412. .. _Data Source Name: http://pear.php.net/manual/en/package.database.db.intro-dsn.php
  413. Examples
  414. ~~~~~~~~
  415. Using a `Data Source Name`_ to create a new database connection::
  416. $conf = array('dsn' => 'pgsql://jon@localhost+unix/logs');
  417. $logger = &Log::singleton('sql', 'log_table', 'ident', $conf);
  418. for ($i = 0; $i < 10; $i++) {
  419. $logger->log("Log entry $i");
  420. }
  421. Using an existing `DB`_ object::
  422. require_once 'DB.php';
  423. $db = &DB::connect('pgsql://jon@localhost+unix/logs');
  424. $conf['db'] = $db;
  425. $logger = &Log::singleton('sql', 'log_table', 'ident', $conf);
  426. for ($i = 0; $i < 10; $i++) {
  427. $logger->log("Log entry $i");
  428. }
  429. The Sqlite Handler
  430. ------------------
  431. :Author: Bertrand Mansion
  432. :Contact: bmansion@mamasam.com
  433. The Sqlite handler sends log events to an Sqlite database using the `native
  434. PHP sqlite functions`_.
  435. It is faster than `the SQL (DB) handler`_ because requests are made directly
  436. to the database without using an abstraction layer. It is also interesting to
  437. note that Sqlite database files can be moved, copied, and deleted on your
  438. system just like any other files, which makes log management easier. Last but
  439. not least, using a database to log your events allows you to use SQL queries
  440. to create reports and statistics.
  441. When using a database and logging a lot of events, it is recommended to split
  442. the database into smaller databases. This is allowed by Sqlite, and you can
  443. later use the Sqlite `ATTACH`_ statement to query your log database files
  444. globally.
  445. If the database does not exist when the log is opened, sqlite will try to
  446. create it automatically. If the log table does not exist, it will also be
  447. automatically created. The table creation uses the following SQL request::
  448. CREATE TABLE log_table (
  449. id INTEGER PRIMARY KEY NOT NULL,
  450. logtime NOT NULL,
  451. ident CHAR(16) NOT NULL,
  452. priority INT NOT NULL,
  453. message
  454. );
  455. Configuration
  456. ~~~~~~~~~~~~~
  457. +-------------------+-----------+---------------+---------------------------+
  458. | Parameter | Type | Default | Description |
  459. +===================+===========+===============+===========================+
  460. | ``filename`` | String | '' `(empty)` | Path to an Sqlite |
  461. | | | | database. |required| |
  462. +-------------------+-----------+---------------+---------------------------+
  463. | ``mode`` | Integer | 0666 | Octal mode used to open |
  464. | | | | the database. |
  465. +-------------------+-----------+---------------+---------------------------+
  466. | ``persistent`` | Boolean | false | Use a persistent |
  467. | | | | connection. |
  468. +-------------------+-----------+---------------+---------------------------+
  469. An already opened database connection can also be passed as parameter instead
  470. of the above configuration. In this case, closing the database connection is
  471. up to the user.
  472. .. _native PHP sqlite functions: http://www.php.net/sqlite
  473. .. _ATTACH: http://www.sqlite.org/lang.html#attach
  474. Examples
  475. ~~~~~~~~
  476. Using a configuration to create a new database connection::
  477. $conf = array('filename' => 'log.db', 'mode' => 0666, 'persistent' => true);
  478. $logger =& Log::factory('sqlite', 'log_table', 'ident', $conf);
  479. $logger->log('logging an event', PEAR_LOG_WARNING);
  480. Using an existing connection::
  481. $db = sqlite_open('log.db', 0666, $error);
  482. $logger =& Log::factory('sqlite', 'log_table', 'ident', $db);
  483. $logger->log('logging an event', PEAR_LOG_WARNING);
  484. sqlite_close($db);
  485. The Syslog Handler
  486. ------------------
  487. The Syslog handler sends log events to the system logging service (syslog on
  488. Unix-like environments or the Event Log on Windows systems). The events are
  489. sent using PHP's `syslog()`_ function.
  490. Facilities
  491. ~~~~~~~~~~
  492. +-------------------+-------------------------------------------------------+
  493. | Constant | Category Description |
  494. +===================+=======================================================+
  495. | ``LOG_AUTH`` | Security / authorization messages; ``LOG_AUTHPRIV`` is|
  496. | | preferred on systems where it is defined. |
  497. +-------------------+-------------------------------------------------------+
  498. | ``LOG_AUTHPRIV`` | Private security / authorization messages |
  499. +-------------------+-------------------------------------------------------+
  500. | ``LOG_CRON`` | Clock daemon (``cron`` and ``at``) |
  501. +-------------------+-------------------------------------------------------+
  502. | ``LOG_DAEMON`` | System daemon processes |
  503. +-------------------+-------------------------------------------------------+
  504. | ``LOG_KERN`` | Kernel messages |
  505. +-------------------+-------------------------------------------------------+
  506. | ``LOG_LOCAL0`` .. | Reserved for local use; **not** available under |
  507. | ``LOG_LOCAL7`` | Windows. |
  508. +-------------------+-------------------------------------------------------+
  509. | ``LOG_LPR`` | Printer subsystem |
  510. +-------------------+-------------------------------------------------------+
  511. | ``LOG_MAIL`` | Mail subsystem |
  512. +-------------------+-------------------------------------------------------+
  513. | ``LOG_NEWS`` | USENET news subsystem |
  514. +-------------------+-------------------------------------------------------+
  515. | ``LOG_SYSLOG`` | Internal syslog messages |
  516. +-------------------+-------------------------------------------------------+
  517. | ``LOG_USER`` | Generic user-level messages |
  518. +-------------------+-------------------------------------------------------+
  519. | ``LOG_UUCP`` | UUCP subsystem |
  520. +-------------------+-------------------------------------------------------+
  521. .. _syslog(): http://www.php.net/syslog
  522. Example
  523. ~~~~~~~
  524. ::
  525. $logger = &Log::singleton('syslog', LOG_LOCAL0, 'ident');
  526. for ($i = 0; $i < 10; $i++) {
  527. $logger->log("Log entry $i");
  528. }
  529. The Window Handler
  530. ------------------
  531. The Window handler sends log events to a separate browser window. The
  532. original idea for this handler was inspired by Craig Davis' Zend.com article
  533. entitled `"JavaScript Power PHP Debugging"`_.
  534. Configuration
  535. ~~~~~~~~~~~~~
  536. +-------------------+-----------+---------------+---------------------------+
  537. | Parameter | Type | Default | Description |
  538. +===================+===========+===============+===========================+
  539. | ``title`` | String | ``Log Output | The title of the output |
  540. | | | Window`` | window. |
  541. +-------------------+-----------+---------------+---------------------------+
  542. | ``colors`` | Array | `ROY G BIV`_ | Mapping of log priorities |
  543. | | | (high to low) | to colors. |
  544. +-------------------+-----------+---------------+---------------------------+
  545. .. _"JavaScript Power PHP Debugging": http://www.zend.com/zend/tut/tutorial-DebugLib.php
  546. .. _ROY G BIV: http://www.cis.rit.edu/
  547. Example
  548. ~~~~~~~
  549. ::
  550. $conf = array('title' => 'Sample Log Output');
  551. $logger = &Log::singleton('win', 'LogWindow', 'ident', $conf);
  552. for ($i = 0; $i < 10; $i++) {
  553. $logger->log("Log entry $i");
  554. }
  555. Composite Handlers
  556. ==================
  557. It is often useful to log events to multiple handlers. The Log package
  558. provides a compositing system that marks this task trivial.
  559. Start by creating the individual log handlers::
  560. $console = &Log::singleton('console', '', 'TEST');
  561. $file = &Log::singleton('file', 'out.log', 'TEST');
  562. Then, construct a composite handler and add the individual handlers as
  563. children of the composite::
  564. $composite = &Log::singleton('composite');
  565. $composite->addChild($console);
  566. $composite->addChild($file);
  567. The composite handler implements the standard ``Log`` interface so you can use
  568. it just like any of the other handlers::
  569. $composite->log('This event will be logged to both handlers.');
  570. Children can be removed from the composite when they're not longer needed::
  571. $composite->removeChild($file);
  572. Log Observers
  573. =============
  574. Log observers provide an implementation of the `observer pattern`_. In the
  575. content of the Log package, they provide a mechanism by which you can examine
  576. (i.e. observe) each event as it is logged. This allows the implementation of
  577. special behavior based on the contents of a log event. For example, the
  578. observer code could send an alert email if a log event contained the string
  579. ``PANIC``.
  580. Creating a log observer involves implementing a subclass of the
  581. ``Log_observer`` class. The subclass must override the base class's
  582. ``notify()`` method. This method is passed a hash containing the event's
  583. priority and event. The subclass's implementation is free to act upon this
  584. information in any way it likes.
  585. Log observers are attached to ``Log`` instances via the ``attach()`` method::
  586. $observer = &Log_observer::factory('yourType');
  587. $logger->attach($observer);
  588. Observers can be detached using the ``detach()`` method::
  589. $logger->detach($observer);
  590. At this time, no concrete ``Log_observer`` implementations are distributed
  591. with the Log package.
  592. .. _observer pattern: http://phppatterns.com/index.php/article/articleview/27/1/1/
  593. Logging From Standard Error Handlers
  594. ====================================
  595. Logging PHP Errors
  596. ------------------
  597. PHP's default error handler can be overridden using the `set_error_handler()`_
  598. function. The custom error handling function can use a global Log instance to
  599. log the PHP errors.
  600. **Note:** Fatal PHP errors cannot be handled by a custom error handler at this
  601. time.
  602. ::
  603. function errorHandler($code, $message, $file, $line)
  604. {
  605. global $logger;
  606. /* Map the PHP error to a Log priority. */
  607. switch ($code) {
  608. case E_WARNING:
  609. case E_USER_WARNING:
  610. $priority = PEAR_LOG_WARNING;
  611. break;
  612. case E_NOTICE:
  613. case E_USER_NOTICE:
  614. $priority = PEAR_LOG_NOTICE;
  615. break;
  616. case E_ERROR:
  617. case E_USER_ERROR:
  618. $priority = PEAR_LOG_ERR;
  619. break;
  620. default:
  621. $priotity = PEAR_LOG_INFO;
  622. }
  623. $logger->log($message . ' in ' . $file . ' at line ' . $line,
  624. $priority);
  625. }
  626. set_error_handler('errorHandler');
  627. trigger_error('This is an information log message.', E_USER_NOTICE);
  628. .. _set_error_handler(): http://www.php.net/set_error_handler
  629. Logging PEAR Errors
  630. -------------------
  631. The Log package can be used with `PEAR::setErrorHandling()`_'s
  632. ``PEAR_ERROR_CALLBACK`` mechanism by writing an error handling function that
  633. uses a global Log instance. Here's an example::
  634. function errorHandler($error)
  635. {
  636. global $logger;
  637. $message = $error->getMessage();
  638. if (!empty($error->backtrace[1]['file'])) {
  639. $message .= ' (' . $error->backtrace[1]['file'];
  640. if (!empty($error->backtrace[1]['line'])) {
  641. $message .= ' at line ' . $error->backtrace[1]['line'];
  642. }
  643. $message .= ')';
  644. }
  645. $logger->log($message, $error->code);
  646. }
  647. PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'errorHandler');
  648. PEAR::raiseError('This is an information log message.', PEAR_LOG_INFO);
  649. .. _PEAR::setErrorHandling(): http://pear.php.net/manual/en/core.pear.pear.seterrorhandling.php
  650. Custom Handlers
  651. ===============
  652. There are times when the standard handlers aren't a perfect match for your
  653. needs. In those situations, the solution might be to write a custom handler.
  654. Using a Custom Handler
  655. ----------------------
  656. Using a custom Log handler is very simple. Once written (see `Writing New
  657. Handlers`_ and `Extending Existing Handlers`_ below), you have the choice of
  658. placing the file in your PEAR installation's main ``Log/`` directory (usually
  659. something like ``/usr/local/lib/php/Log`` or ``C:\php\pear\Log``), where it
  660. can be found and use by any PHP application on the system, or placing the file
  661. somewhere in your application's local hierarchy and including it before the
  662. the custom Log object is constructed.
  663. Method 1: Handler in the Standard Location
  664. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  665. After copying the handler file to your PEAR installation's ``Log/`` directory,
  666. simply treat the handler as if it were part of the standard distributed. If
  667. your handler is named ``custom`` (and therefore implemented by a class named
  668. ``Log_custom``)::
  669. require_once 'Log.php';
  670. $logger = &Log::factory('custom', '', 'CUSTOM');
  671. Method 2: Handler in a Custom Location
  672. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  673. If you prefer storing your handler in your application's local hierarchy,
  674. you'll need to include that file before you can create a Log instance based on
  675. it.
  676. ::
  677. require_once 'Log.php';
  678. require_once 'LocalHandlers/custom.php';
  679. $logger = &Log::factory('custom', '', 'CUSTOM');
  680. Writing New Handlers
  681. --------------------
  682. TODO
  683. Extending Existing Handlers
  684. ---------------------------
  685. TODO
  686. .. |required| replace:: **[required]**
  687. .. vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab textwidth=78 ft=rst: