PHPackages                             ubccr/log - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. ubccr/log

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

ubccr/log
=========

PEAR Logging Framework

1.13.2(8y ago)014.7k↑36.4%MITPHPPHP &gt;5.2

Since Jul 12Pushed 8y ago3 watchersCompare

[ Source](https://github.com/ubccr/Log)[ Packagist](https://packagist.org/packages/ubccr/log)[ Docs](http://pear.github.io/Log/)[ RSS](/packages/ubccr-log/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (2)Versions (6)Used By (0)

The Log Package
===============

[](#the-log-package)

User Documentation
------------------

[](#user-documentation)

Author:Jon PariseContact:Contents

- [1 Using Log Handlers](#using-log-handlers)
    - [1.1 Creating a Log Object](#creating-a-log-object)
        - [1.1.1 The Factory Method](#the-factory-method)
        - [1.1.2 The Singleton Method](#the-singleton-method)
        - [1.1.3 Direct Instantiation](#direct-instantiation)
    - [1.2 Configuring a Handler](#configuring-a-handler)
    - [1.3 Logging an Event](#logging-an-event)
    - [1.4 Log Levels](#log-levels)
    - [1.5 Log Level Masks](#log-level-masks)
    - [1.6 Log Line Format](#log-line-format)
    - [1.7 Flushing Log Events](#flushing-log-events)
- [2 Standard Log Handlers](#standard-log-handlers)
    - [2.1 The Console Handler](#the-console-handler)
        - [2.1.1 Configuration](#configuration)
        - [2.1.2 Example](#example)
    - [2.2 The Display Handler](#the-display-handler)
        - [2.2.1 Configuration](#id2)
        - [2.2.2 Example](#id3)
    - [2.3 The Error\_Log Handler](#the-error-log-handler)
        - [2.3.1 Configuration](#id4)
        - [2.3.2 Error\_Log Types](#error-log-types)
        - [2.3.3 Example](#id5)
    - [2.4 The File Handler](#the-file-handler)
        - [2.4.1 Configuration](#id6)
        - [2.4.2 Example](#id8)
    - [2.5 The Firebug Handler](#the-firebug-handler)
        - [2.5.1 Configuration](#id9)
        - [2.5.2 Example](#id11)
    - [2.6 The Mail Handler](#the-mail-handler)
        - [2.6.1 Configuration](#id12)
        - [2.6.2 Example](#id14)
    - [2.7 The MDB2 Handler](#the-mdb2-handler)
        - [2.7.1 Configuration](#id15)
    - [2.8 The Null Handler](#the-null-handler)
        - [2.8.1 Example](#id16)
    - [2.9 The SQL (DB) Handler](#the-sql-db-handler)
        - [2.9.1 The Log Table](#the-log-table)
        - [2.9.2 Configuration](#id17)
        - [2.9.3 Examples](#examples)
    - [2.10 The Sqlite Handler](#the-sqlite-handler)
        - [2.10.1 Configuration](#id18)
        - [2.10.2 Examples](#id19)
    - [2.11 The Syslog Handler](#the-syslog-handler)
        - [2.11.1 Configuration](#id20)
        - [2.11.2 Facilities](#facilities)
        - [2.11.3 Example](#id21)
    - [2.12 The Window Handler](#the-window-handler)
        - [2.12.1 Configuration](#id22)
        - [2.12.2 Example](#id23)
- [3 Composite Handlers](#composite-handlers)
- [4 Log Observers](#log-observers)
- [5 Logging From Standard Error Handlers](#logging-from-standard-error-handlers)
    - [5.1 Logging PHP Errors](#logging-php-errors)
    - [5.2 Logging PHP Assertions](#logging-php-assertions)
    - [5.3 Logging PHP Exceptions](#logging-php-exceptions)
    - [5.4 Logging PEAR Errors](#logging-pear-errors)
- [6 Custom Handlers](#custom-handlers)
    - [6.1 Using a Custom Handler](#using-a-custom-handler)
        - [6.1.1 Method 1: Handler in the Standard Location](#method-1-handler-in-the-standard-location)
        - [6.1.2 Method 2: Handler in a Custom Location](#method-2-handler-in-a-custom-location)
    - [6.2 Writing New Handlers](#writing-new-handlers)
    - [6.3 Extending Existing Handlers](#extending-existing-handlers)
    - [6.4 Handler Methods](#handler-methods)
        - [6.4.1 bool open()](#bool-open)
        - [6.4.2 bool close()](#bool-close)
        - [6.4.3 bool flush()](#bool-flush)
        - [6.4.4 bool log($message, $priority = null)](#bool-log-message-priority-null)
    - [6.5 Utility Methods](#utility-methods)
        - [6.5.1 string \_extractMessage($message)](#string-extractmessage-message)
        - [6.5.2 string \_format($format, $timestamp, $priority, $message)](#string-format-format-timestamp-priority-message)
        - [6.5.3 bool \_isMasked($priority)](#bool-ismasked-priority)
        - [6.5.4 void \_announce($event)](#void-announce-event)

[1 Using Log Handlers](#id25)
-----------------------------

[](#1using-log-handlers)

The Log package is implemented as a framework that supports the notion of backend-specific log handlers. The base logging object (defined by the [Log class](http://cvs.php.net/viewvc.cgi/pear/Log/Log.php)) is primarily an abstract interface to the currently configured handler.

A wide variety of handlers are distributed with the Log package, and, should none of them fit your application's needs, it's easy to [write your own](#custom-handlers).

### [1.1 Creating a Log Object](#id26)

[](#11creating-a-log-object)

There are three ways to create Log objects:

> - Using the `Log::factory()` method
> - Using the `Log::singleton()` method
> - Direct instantiation

#### [1.1.1 The Factory Method](#id27)

[](#111the-factory-method)

The `Log::factory()` method implements the [Factory Pattern](http://wikipedia.org/wiki/Factory_method_pattern). It allows for the parameterized construction of concrete Log instances at runtime. The first parameter to the `Log::factory()` method indicates the name of the concrete handler to create. The rest of the parameters will be passed on to the handler's constructor (see [Configuring a Handler](#configuring-a-handler) below).

The new `Log` instance is returned by reference.

```
require_once 'Log.php';

$console = Log::factory('console', '', 'TEST');
$console->log('Logging to the console.');

$file = Log::factory('file', 'out.log', 'TEST');
$file->log('Logging to out.log.');
```

#### [1.1.2 The Singleton Method](#id28)

[](#112the-singleton-method)

The `Log::singleton()` method implements the [Singleton Pattern](http://wikipedia.org/wiki/Singleton_pattern). The singleton pattern ensures that only a single instance of a given log type and configuration is ever created. This has two benefits: first, it prevents duplicate `Log` instances from being constructed, and, second, it gives all of your code access to the same `Log` instance. The latter is especially important when logging to files because only a single file handler will need to be managed.

The `Log::singleton()` method's parameters match the `Log::factory()`method. The new `Log` instance is returned by reference.

```
require_once 'Log.php';

/* Same construction parameters */
$a = Log::singleton('console', '', 'TEST');
$b = Log::singleton('console', '', 'TEST');

if ($a === $b) {
    echo '$a and $b point to the same Log instance.' . "\n";
}

/* Different construction parameters */
$c = Log::singleton('console', '', 'TEST1');
$d = Log::singleton('console', '', 'TEST2');

if ($c !== $d) {
    echo '$c and $d point to different Log instances.' . "\n";
}
```

#### [1.1.3 Direct Instantiation](#id29)

[](#113direct-instantiation)

It is also possible to directly instantiate concrete `Log` handler instances. However, this method is **not recommended** because it creates a tighter coupling between your application code and the Log package than is necessary. Use of [the factory method](#the-factory-method) or [the singleton method](#the-singleton-method) is preferred.

### [1.2 Configuring a Handler](#id30)

[](#12configuring-a-handler)

A log handler's configuration is determined by the arguments used in its construction. Here's an overview of those parameters:

```
/* Using the factory method ... */
Log::factory($handler, $name, $ident, $conf, $maxLevel);

/* Using the singleton method ... */
Log::singleton($handler, $name, $ident, $conf, $maxLevel);

/* Using direct instantiation ... */
new Log_handler($name, $ident, $conf, $maxLevel);
```

ParameterTypeDescription`$handler`StringThe type of Log handler to construct. This parameter is only available when [the factory method](#the-factory-method) or [the singleton method](#the-singleton-method) are used.`$name`StringThe name of the log resource to which the events will be logged. The use of this value is determined by the handler's implementation. It defaults to an empty string.`$ident`StringAn identification string that will be included in all log events logged by this handler. This value defaults to an empty string and can be changed at runtime using the `setIdent()`method.`$conf`ArrayAssociative array of key-value pairs that are used to specify any handler-specific settings.`$level`IntegerLog messages up to and including this level. This value defaults to `PEAR_LOG_DEBUG`. See [Log Levels](#log-levels) and [Log Level Masks](#log-level-masks).### [1.3 Logging an Event](#id31)

[](#13logging-an-event)

Events are logged using the `log()` method:

```
$logger->log('Message', PEAR_LOG_NOTICE);
```

The first argument contains the log event's message. Even though the event is always logged as a string, it is possible to pass an object to the `log()`method. If the object implements a `getString()` method, a `toString()`method or Zend Engine 2's special `__toString()` casting method, it will be used to determine the object's string representation. Otherwise, the [serialized](http://www.php.net/serialize) form of the object will be logged.

The second, optional argument specifies the log event's priority. See the [Log Levels](#log-levels) table for the complete list of priorities. The default priority is PEAR\_LOG\_INFO.

The `log()` method will return `true` if the event was successfully logged.

"Shortcut" methods are also available for logging an event at a specific log level. See the [Log Levels](#log-levels) table for the complete list.

### [1.4 Log Levels](#id32)

[](#14log-levels)

This table is ordered by highest priority (`PEAR_LOG_EMERG`) to lowest priority (`PEAR_LOG_DEBUG`).

LevelShortcutDescription`PEAR_LOG_EMERG``emerg()`System is unusable`PEAR_LOG_ALERT``alert()`Immediate action required`PEAR_LOG_CRIT``crit()`Critical conditions`PEAR_LOG_ERR``err()`Error conditions`PEAR_LOG_WARNING``warning()`Warning conditions`PEAR_LOG_NOTICE``notice()`Normal but significant`PEAR_LOG_INFO``info()`Informational`PEAR_LOG_DEBUG``debug()`Debug-level messages### [1.5 Log Level Masks](#id33)

[](#15log-level-masks)

Defining a log level mask allows you to include and/or exclude specific levels of events from being logged. The `$level` construction parameter (see [Configuring a Handler](#configuring-a-handler)) uses this mechanism to exclude log events below a certain priority, and it's possible to define more complex masks once the Log object has been constructed.

Each priority has a specific mask associated with it. To compute a priority's mask, use the static `Log::MASK()` method:

```
$mask = Log::MASK(PEAR_LOG_INFO);
```

To compute the mask for all priorities up to, and including, a certain level, use the `Log::MAX()` static method:

```
$mask = Log::MAX(PEAR_LOG_INFO);
```

To compute the mask for all priorities greater than or equal to a certain level, use the `Log::MIN()` static method:

```
$mask = Log::MIN(PEAR_LOG_INFO);
```

The apply the mask, use the `setMask()` method:

```
$logger->setMask($mask);
```

Masks can be be combined using bitwise operations. To restrict logging to only those events marked as `PEAR_LOG_NOTICE` or `PEAR_LOG_DEBUG`:

```
$mask = Log::MASK(PEAR_LOG_NOTICE) | Log::MASK(PEAR_LOG_DEBUG);
$logger->setMask($mask);
```

For convenience, two special masks are predefined: `PEAR_LOG_NONE` and `PEAR_LOG_ALL`. `PEAR_LOG_ALL` is especially useful for excluding only specific priorities:

```
$mask = PEAR_LOG_ALL ^ Log::MASK(PEAR_LOG_NOTICE);
$logger->setMask($mask);
```

It is also possible to retrieve and modify a Log object's existing mask:

```
$mask = $logger->getMask() | Log::MASK(PEAR_LOG_INFO);
$logger->setMask($mask);
```

### [1.6 Log Line Format](#id34)

[](#16log-line-format)

Most log handlers support configurable line formats. The following is a list of special tokens that will be expanded at runtime with contextual information related to the log event. Each token has an alternate shorthand notation, as well.

TokenAlternateDescription`%{timestamp}``%1$s`Timestamp. This is often configurable.`%{ident}``%2$s`The log handler's identification string.`%{priority}``%3$s`The log event's priority.`%{message}``%4$s`The log event's message text.`%{file}``%5$s`The full filename of the logging file.`%{line}``%6$s`The line number on which the event occured.`%{function}``%7$s`The function from which the event occurred.`%{class}``%8$s`The class in which the event occurred.### [1.7 Flushing Log Events](#id35)

[](#17flushing-log-events)

Some log handlers (such as [the console handler](#the-console-handler)) support explicit "buffering". When buffering is enabled, log events won't actually be written to the output stream until the handler is closed. Other handlers (such as [the file handler](#the-file-handler)) support implicit buffering because they use the operating system's IO routines, which may buffer the output.

It's possible to force these handlers to flush their output, however, by calling their `flush()` method:

```
$conf = array('buffering' => true);
$logger = Log::singleton('console', '', 'test', $conf);

for ($i = 0; $i < 10; $i++) {
    $logger->log('This event will be buffered.');
}

/* Flush all of the buffered log events. */
$logger->flush();

for ($i = 0; $i < 10; $i++) {
    $logger->log('This event will be buffered.');
}

/* Implicitly flush the buffered events on close. */
$logger->close();
```

At this time, the `flush()` method is only implemented by [the console handler](#the-console-handler), [the file handler](#the-file-handler), [the Firebug handler](#the-firebug-handler), and [the mail handler](#the-mail-handler).

[2 Standard Log Handlers](#id36)
--------------------------------

[](#2standard-log-handlers)

### [2.1 The Console Handler](#id37)

[](#21the-console-handler)

The Console handler outputs log events directly to the console. It supports output buffering and configurable string formats.

#### [2.1.1 Configuration](#id38)

[](#211configuration)

ParameterTypeDefaultDescription`stream`File[STDOUT](http://www.php.net/wrappers.php)The output stream to use.`buffering`BooleanFalseShould the output be buffered until shutdown?`lineFormat`String`%1$s %2$s[%3$s] %4$s`[Log line format](#log-line-format)specification.`timeFormat`String`%b %d%H:%M:%S`Time stamp format (for [strftime](http://www.php.net/strftime)).#### [2.1.2 Example](#id39)

[](#212example)

```
$logger = Log::singleton('console', '', 'ident');
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

### [2.2 The Display Handler](#id40)

[](#22the-display-handler)

The Display handler simply prints the log events back to the browser. It respects the `error_prepend_string` and `error_append_string` [error handling values](http://www.php.net/errorfunc) and is useful when [logging from standard error handlers](#logging-from-standard-error-handlers).

#### [2.2.1 Configuration](#id41)

[](#221configuration)

ParameterTypeDefaultDescription`lineFormat`String`%3$s:%4$s`[Log line format](#log-line-format)specification.`timeFormat`String`%b %d%H:%M:%S`Time stamp format (for [strftime](http://www.php.net/strftime)).`error_prepend`StringPHP INI valueThis string will be prepended to the line format.`error_append`StringPHP INI valueThis string will be appended to the line format.`linebreak`String`\n`This string is used to represent a line break.`rawText`BooleanFalseShould message text be passed directly to the log system? Otherwise, it will be converted to an HTML-safe representation.#### [2.2.2 Example](#id42)

[](#222example)

```
$conf = array('error_prepend' => '',
              'error_append'  => '');
$logger = Log::singleton('display', '', '', $conf, PEAR_LOG_DEBUG);
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

### [2.3 The Error\_Log Handler](#id43)

[](#23the-error_log-handler)

The Error\_Log handler sends log events to PHP's [error\_log()](http://www.php.net/error_log) function.

#### [2.3.1 Configuration](#id44)

[](#231configuration)

ParameterTypeDefaultDescription`destination`String'' (empty)Optional destination value for [error\_log()](http://www.php.net/error_log). See [Error\_Log Types](#error-log-types) for more details.`extra_headers`String'' (empty)Additional headers to pass to the [mail()](http://www.php.net/mail) function when the `PEAR_LOG_TYPE_MAIL`type is specified.`lineFormat`String`%2$s: %4$s`[Log line format](#log-line-format)specification.`timeFormat`String`%b %d%H:%M:%S`Time stamp format (for [strftime](http://www.php.net/strftime)).#### [2.3.2 Error\_Log Types](#id45)

[](#232error_log-types)

All of the available log types are detailed in the [error\_log()](http://www.php.net/error_log) section of the PHP manual. For your convenience, the Log package also defines the following constants that can be used for the `$name` handler construction parameter.

ConstantDescription`PEAR_LOG_TYPE_SYSTEM`Log events are sent to PHP's system logger, which uses the operating system's logging mechanism or a file (depending on the value of the [error\_log configuration directive](http://www.php.net/errorfunc#ini.error-log)).`PEAR_LOG_TYPE_MAIL`Log events are sent via email to the address specified in the `destination` value.`PEAR_LOG_TYPE_DEBUG`Log events are sent through PHP's debugging connection. This will only work if [remote debugging](http://www.php.net/install.configure#install.configure.enable-debugger) has been enabled. The `destination` value is used to specify the host name or IP address of the target socket.`PEAR_LOG_TYPE_FILE`Log events will be appended to the file named by the `destination` value.`PEAR_LOG_TYPE_SAPI`Log events will be sent directly to the SAPI logging handler.#### [2.3.3 Example](#id46)

[](#233example)

```
$logger = Log::singleton('error_log', PEAR_LOG_TYPE_SYSTEM, 'ident');
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

### [2.4 The File Handler](#id47)

[](#24the-file-handler)

The File handler writes log events to a text file using configurable string formats.

#### [2.4.1 Configuration](#id48)

[](#241configuration)

ParameterTypeDefaultDescription`append`BooleanTrueShould new log entries be append to an existing log file, or should the a new log file overwrite an existing one?`locking`BooleanFalseShould advisory file locking (using [flock](http://www.php.net/flock)) be used?`mode`Integer0644Octal representation of the log file's permissions mode.`dirmode`Integer0755Octal representation of the file permission mode that will be used when creating directories that do not already exist.`eol`StringOS defaultThe end-of-line character sequence.`lineFormat`String`%1$s %2$s[%3$s] %4$s`[Log line format](#log-line-format)specification.`timeFormat`String`%b %d%H:%M:%S`Time stamp format (for [strftime](http://www.php.net/strftime)).The file handler will only attempt to set the `mode` value if it was responsible for creating the file.

#### [2.4.2 Example](#id49)

[](#242example)

```
$conf = array('mode' => 0600, 'timeFormat' => '%X %x');
$logger = Log::singleton('file', 'out.log', 'ident', $conf);
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

### [2.5 The Firebug Handler](#id50)

[](#25the-firebug-handler)

The Firebug handler outputs log events to the [Firebug](http://www.getfirebug.com/) console. It supports output buffering and configurable string formats.

#### [2.5.1 Configuration](#id51)

[](#251configuration)

ParameterTypeDefaultDescription`buffering`BooleanFalseShould the output be buffered until shutdown?`lineFormat`String`%2$s [%3$s]%4$s`[Log line format](#log-line-format)specification.`timeFormat`String`%b %d%H:%M:%S`Time stamp format (for [strftime](http://www.php.net/strftime)).#### [2.5.2 Example](#id52)

[](#252example)

```
$logger = Log::singleton('firebug', '', 'ident');
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

### [2.6 The Mail Handler](#id53)

[](#26the-mail-handler)

The Mail handler aggregates a session's log events and sends them in the body of an email message using either the [PEAR Mail](http://pear.php.net/package/Mail) package or PHP's native [mail()](http://www.php.net/mail) function.

If an empty `mailBackend` value is specified, the [mail()](http://www.php.net/mail) function will be used instead of the [PEAR Mail](http://pear.php.net/package/Mail) package.

Multiple recipients can be specified by separating their email addresses with commas in the `$name` construction parameter.

#### [2.6.1 Configuration](#id54)

[](#261configuration)

ParameterTypeDefaultDescription`from`Stringsendmail\_from INI valueValue for the message's `From:` header.`subject`String`[Log_mail]Log message`Value for the message's `Subject:` header.`preamble`String`` (empty)Preamble for the message.`lineFormat`String`%1$s %2$s[%3$s] %4$s`[Log line format](#log-line-format)specification.`timeFormat`String`%b %d%H:%M:%S`Time stamp format (for [strftime](http://www.php.net/strftime)).`mailBackend`String`` (empty)Name of the Mail package backend to use.`mailParams`Array(empty)Array of parameters that will be passed to the Mail package backend.#### [2.6.2 Example](#id55)

[](#262example)

```
$conf = array('subject' => 'Important Log Events');
$logger = Log::singleton('mail', 'webmaster@example.com', 'ident', $conf);
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

### [2.7 The MDB2 Handler](#id56)

[](#27the-mdb2-handler)

The MDB2 handler is similar to [the SQL (DB) handler](#the-sql-db-handler), but instead of using the PEAR DB package, it uses the [MDB2 database abstraction package](http://pear.php.net/package/MDB2).

#### [2.7.1 Configuration](#id57)

[](#271configuration)

ParameterTypeDefaultDescription`dsn`Mixed'' (empty)A [Data Source Name](http://pear.php.net/manual/en/package.database.db.intro-dsn.php). **\[required\]**`options`Array`persistent`An array of [MDB2](http://pear.php.net/package/MDB2)options.`db`ObjectNULLAn existing [MDB2](http://pear.php.net/package/MDB2)object. If specified, this object will be used, and `dsn` will be ignored.`sequence`String`log_id`The name of the sequence to use when generating unique event IDs. Under many databases, this will be used as the name of the sequence table.`identLimit`Integer16The maximum length of the `ident` string. **Changing this value may require updates to the SQL schema, as well.**`singleton`BooleanfalseIs true, use a singleton database object using [MDB2::singleton()](http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2.html#methodsingleton).### [2.8 The Null Handler](#id58)

[](#28the-null-handler)

The Null handler simply consumes log events (akin to sending them to `/dev/null`). [Log level masks](#log-level-masks) are respected, and the event will still be sent to any registered [log observers](#log-observers).

#### [2.8.1 Example](#id59)

[](#281example)

```
$logger = Log::singleton('null');
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

### [2.9 The SQL (DB) Handler](#id60)

[](#29the-sql-db-handler)

The SQL handler sends log events to a database using [PEAR's DB abstraction layer](http://pear.php.net/package/DB).

**Note:** Due to the constraints of the default database schema, the SQL handler limits the length of the `$ident` string to sixteen (16) characters. This limit can be adjusted using the `identLimit` configuration parameter.

#### [2.9.1 The Log Table](#id61)

[](#291the-log-table)

The default SQL table used by this handler looks like this:

```
CREATE TABLE log_table (
    id          INT NOT NULL,
    logtime     TIMESTAMP NOT NULL,
    ident       CHAR(16) NOT NULL,
    priority    INT NOT NULL,
    message     VARCHAR(200),
    PRIMARY KEY (id)
);
```

This is the "lowest common denominator" that should work across all SQL compliant database. You may want to make database- or site-specific changes to this schema to support your specific needs, however. For example, [PostgreSQL](http://www.postgresql.org/) users may prefer to use a `TEXT` type for the `message`field.

#### [2.9.2 Configuration](#id62)

[](#292configuration)

ParameterTypeDefaultDescription`dsn`Mixed'' (empty)A [Data Source Name](http://pear.php.net/manual/en/package.database.db.intro-dsn.php). **\[required\]**`sql`String`INSERT INTO $table (id, logtime, ident, priority, message) VALUES(?, CURRENT_TIMESTAMP, ?, ?, ?)`SQL insertion statement.`options`Array`persistent`An array of [DB](http://pear.php.net/package/DB) options.`db`ObjectNULLAn existing [DB](http://pear.php.net/package/DB) object. If specified, this object will be used, and `dsn`will be ignored.`sequence`String`log_id`The name of the sequence to use when generating unique event IDs. Under many databases, this will be used as the name of the sequence table.`identLimit`Integer16The maximum length of the `ident` string. **Changing this value may require updates to the SQL schema, as well.**The name of the database table to which the log entries will be written is specified using the `$name` construction parameter (see [Configuring a Handler](#configuring-a-handler)).

#### [2.9.3 Examples](#id63)

[](#293examples)

Using a [Data Source Name](http://pear.php.net/manual/en/package.database.db.intro-dsn.php) to create a new database connection:

```
$conf = array('dsn' => 'pgsql://jon@localhost+unix/logs');
$logger = Log::singleton('sql', 'log_table', 'ident', $conf);
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

Using an existing [DB](http://pear.php.net/package/DB) object:

```
require_once 'DB.php';
$db = &DB::connect('pgsql://jon@localhost+unix/logs');

$conf['db'] = $db;
$logger = Log::singleton('sql', 'log_table', 'ident', $conf);
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

### [2.10 The Sqlite Handler](#id64)

[](#210the-sqlite-handler)

Author:Bertrand MansionThe Sqlite handler sends log events to an Sqlite database using the [native PHP sqlite functions](http://www.php.net/sqlite).

It is faster than [the SQL (DB) handler](#the-sql-db-handler) because requests are made directly to the database without using an abstraction layer. It is also interesting to note that Sqlite database files can be moved, copied, and deleted on your system just like any other files, which makes log management easier. Last but not least, using a database to log your events allows you to use SQL queries to create reports and statistics.

When using a database and logging a lot of events, it is recommended to split the database into smaller databases. This is allowed by Sqlite, and you can later use the Sqlite [ATTACH](http://www.sqlite.org/lang.html#attach) statement to query your log database files globally.

If the database does not exist when the log is opened, sqlite will try to create it automatically. If the log table does not exist, it will also be automatically created. The table creation uses the following SQL request:

```
CREATE TABLE log_table (
    id          INTEGER PRIMARY KEY NOT NULL,
    logtime     NOT NULL,
    ident       CHAR(16) NOT NULL,
    priority    INT NOT NULL,
    message
);
```

#### [2.10.1 Configuration](#id65)

[](#2101configuration)

ParameterTypeDefaultDescription`filename`String'' (empty)Path to an Sqlite database. **\[required\]**`mode`Integer0666Octal mode used to open the database.`persistent`BooleanfalseUse a persistent connection.An already opened database connection can also be passed as parameter instead of the above configuration. In this case, closing the database connection is up to the user.

#### [2.10.2 Examples](#id66)

[](#2102examples)

Using a configuration to create a new database connection:

```
$conf = array('filename' => 'log.db', 'mode' => 0666, 'persistent' => true);
$logger = Log::factory('sqlite', 'log_table', 'ident', $conf);
$logger->log('logging an event', PEAR_LOG_WARNING);
```

Using an existing connection:

```
$db = sqlite_open('log.db', 0666, $error);
$logger = Log::factory('sqlite', 'log_table', 'ident', $db);
$logger->log('logging an event', PEAR_LOG_WARNING);
sqlite_close($db);
```

### [2.11 The Syslog Handler](#id67)

[](#211the-syslog-handler)

The Syslog handler sends log events to the system logging service (syslog on Unix-like environments or the Event Log on Windows systems). The events are sent using PHP's [syslog()](http://www.php.net/syslog) function.

#### [2.11.1 Configuration](#id68)

[](#2111configuration)

ParameterTypeDefaultDescription`inherit`BooleanfalseInherit the current syslog connection for this process, or start a new one via [openlog()](http://www.php.net/openlog)?`reopen`BooleanfalseReopen the syslog connection for each log event?`maxLength`Integer500Maximum message length that will be sent to the [syslog()](http://www.php.net/syslog) function. Longer messages will be split across multiple [syslog()](http://www.php.net/syslog) calls.`lineFormat`String`%4$s`[Log line format](#log-line-format)specification.`timeFormat`String`%b %d%H:%M:%S`Time stamp format (for [strftime](http://www.php.net/strftime)).#### [2.11.2 Facilities](#id69)

[](#2112facilities)

ConstantCategory Description`LOG_AUTH`Security / authorization messages; `LOG_AUTHPRIV` is preferred on systems where it is defined.`LOG_AUTHPRIV`Private security / authorization messages`LOG_CRON`Clock daemon (`cron` and `at`)`LOG_DAEMON`System daemon processes`LOG_KERN`Kernel messages`LOG_LOCAL0` .. `LOG_LOCAL7`Reserved for local use; **not** available under Windows.`LOG_LPR`Printer subsystem`LOG_MAIL`Mail subsystem`LOG_NEWS`USENET news subsystem`LOG_SYSLOG`Internal syslog messages`LOG_USER`Generic user-level messages`LOG_UUCP`UUCP subsystem#### [2.11.3 Example](#id70)

[](#2113example)

```
$logger = Log::singleton('syslog', LOG_LOCAL0, 'ident');
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

### [2.12 The Window Handler](#id71)

[](#212the-window-handler)

The Window handler sends log events to a separate browser window. The original idea for this handler was inspired by Craig Davis' Zend.com article entitled ["JavaScript Power PHP Debugging"](http://www.zend.com/zend/tut/tutorial-DebugLib.php).

#### [2.12.1 Configuration](#id72)

[](#2121configuration)

ParameterTypeDefaultDescription`title`String`Log OutputWindow`The title of the output window.`styles`Array[ROY G BIV](http://www.cis.rit.edu/)(high to low)Mapping of log priorities to CSS styles.**Note:** The Window handler may not work reliably when PHP's [output buffering](http://www.php.net/outcontrol) system is enabled.

#### [2.12.2 Example](#id73)

[](#2122example)

```
$conf = array('title' => 'Sample Log Output');
$logger = Log::singleton('win', 'LogWindow', 'ident', $conf);
for ($i = 0; $i < 10; $i++) {
    $logger->log("Log entry $i");
}
```

[3 Composite Handlers](#id74)
-----------------------------

[](#3composite-handlers)

It is often useful to log events to multiple handlers. The Log package provides a compositing system that marks this task trivial.

Start by creating the individual log handlers:

```
$console = Log::factory('console', '', 'TEST');
$file = Log::factory('file', 'out.log', 'TEST');
```

Then, construct a composite handler and add the individual handlers as children of the composite:

```
$composite = Log::singleton('composite');
$composite->addChild($console);
$composite->addChild($file);
```

The composite handler implements the standard `Log` interface so you can use it just like any of the other handlers:

```
$composite->log('This event will be logged to both handlers.');
```

Children can be removed from the composite when they're not longer needed:

```
$composite->removeChild($file);
```

[4 Log Observers](#id75)
------------------------

[](#4log-observers)

Log observers provide an implementation of the [observer pattern](http://wikipedia.org/wiki/Observer_pattern). In the content of the Log package, they provide a mechanism by which you can examine (i.e. observe) each event as it is logged. This allows the implementation of special behavior based on the contents of a log event. For example, the observer code could send an alert email if a log event contained the string `PANIC`.

Creating a log observer involves implementing a subclass of the `Log_observer` class. The subclass must override the base class's `notify()` method. This method is passed a hash containing the event's priority and event. The subclass's implementation is free to act upon this information in any way it likes.

Log observers are attached to `Log` instances via the `attach()` method:

```
$observer = Log_observer::factory('yourType');
$logger->attach($observer);
```

Observers can be detached using the `detach()` method:

```
$logger->detach($observer);
```

At this time, no concrete `Log_observer` implementations are distributed with the Log package.

[5 Logging From Standard Error Handlers](#id76)
-----------------------------------------------

[](#5logging-from-standard-error-handlers)

### [5.1 Logging PHP Errors](#id77)

[](#51logging-php-errors)

PHP's default error handler can be overridden using the [set\_error\_handler()](http://www.php.net/set_error_handler)function. The custom error handling function can use a global Log instance to log the PHP errors.

**Note:** Fatal PHP errors cannot be handled by a custom error handler at this time.

```
function errorHandler($code, $message, $file, $line)
{
    global $logger;

    /* Map the PHP error to a Log priority. */
    switch ($code) {
    case E_WARNING:
    case E_USER_WARNING:
        $priority = PEAR_LOG_WARNING;
        break;
    case E_NOTICE:
    case E_USER_NOTICE:
        $priority = PEAR_LOG_NOTICE;
        break;
    case E_ERROR:
    case E_USER_ERROR:
        $priority = PEAR_LOG_ERR;
        break;
    default:
        $priority = PEAR_LOG_INFO;
    }

    $logger->log($message . ' in ' . $file . ' at line ' . $line,
                 $priority);
}

set_error_handler('errorHandler');
trigger_error('This is an information log message.', E_USER_NOTICE);
```

### [5.2 Logging PHP Assertions](#id78)

[](#52logging-php-assertions)

PHP allows user-defined [assert()](http://www.php.net/assert) callback handlers. The assertion callback is configured using the [assert\_options()](http://www.php.net/assert_options) function.

```
function assertCallback($file, $line, $message)
{
    global $logger;

    $logger->log($message . ' in ' . $file . ' at line ' . $line,
                 PEAR_LOG_ALERT);
}

assert_options(ASSERT_CALLBACK, 'assertCallback');
assert(false);
```

### [5.3 Logging PHP Exceptions](#id79)

[](#53logging-php-exceptions)

PHP 5 and later support the concept of [exceptions](http://www.php.net/exceptions). A custom exception handler can be assigned using the [set\_exception\_handler()](http://www.php.net/set_exception_handler) function.

```
function exceptionHandler($exception)
{
    global $logger;

    $logger->log($exception->getMessage(), PEAR_LOG_ALERT);
}

set_exception_handler('exceptionHandler');
throw new Exception('Uncaught Exception');
```

### [5.4 Logging PEAR Errors](#id80)

[](#54logging-pear-errors)

The Log package can be used with [PEAR::setErrorHandling()](http://pear.php.net/manual/en/core.pear.pear.seterrorhandling.php)'s `PEAR_ERROR_CALLBACK` mechanism by writing an error handling function that uses a global Log instance. Here's an example:

```
function errorHandler($error)
{
    global $logger;

    $message = $error->getMessage();

    if (!empty($error->backtrace[1]['file'])) {
        $message .= ' (' . $error->backtrace[1]['file'];
        if (!empty($error->backtrace[1]['line'])) {
            $message .= ' at line ' . $error->backtrace[1]['line'];
        }
        $message .= ')';
    }

    $logger->log($message, $error->code);
}

PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'errorHandler');
PEAR::raiseError('This is an information log message.', PEAR_LOG_INFO);
```

[6 Custom Handlers](#id81)
--------------------------

[](#6custom-handlers)

There are times when the standard handlers aren't a perfect match for your needs. In those situations, the solution might be to write a custom handler.

### [6.1 Using a Custom Handler](#id82)

[](#61using-a-custom-handler)

Using a custom Log handler is very simple. Once written (see [Writing New Handlers](#writing-new-handlers) and [Extending Existing Handlers](#extending-existing-handlers) below), you have the choice of placing the file in your PEAR installation's main `Log/` directory (usually something like `/usr/local/lib/php/Log` or `C:\php\pear\Log`), where it can be found and use by any PHP application on the system, or placing the file somewhere in your application's local hierarchy and including it before the the custom Log object is constructed.

#### [6.1.1 Method 1: Handler in the Standard Location](#id83)

[](#611method-1-handler-in-the-standard-location)

After copying the handler file to your PEAR installation's `Log/` directory, simply treat the handler as if it were part of the standard distributed. If your handler is named `custom` (and therefore implemented by a class named `Log_custom`):

```
require_once 'Log.php';

$logger = Log::factory('custom', '', 'CUSTOM');
```

#### [6.1.2 Method 2: Handler in a Custom Location](#id84)

[](#612method-2-handler-in-a-custom-location)

If you prefer storing your handler in your application's local hierarchy, you'll need to include that file before you can create a Log instance based on it.

```
require_once 'Log.php';
require_once 'LocalHandlers/custom.php';

$logger = Log::factory('custom', '', 'CUSTOM');
```

### [6.2 Writing New Handlers](#id85)

[](#62writing-new-handlers)

Writing a new Log handler is as simple as authoring a new class that extends the `Log` class and that implements a relatively small set of standard methods.

Every handler's class name must start with `Log_` in order for it to be recognized by the Log package.

```
class Log_custom extends Log
```

The handler's constructor will be called with four parameters. These values are discussed in detail in the [Configuring a Handler](#configuring-a-handler) section.

```
Log_custom($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG)
```

The constructor is responsible for configuring the handler based on these values. Handler-specific parameters are passed as part of the `$conf`array. At a minimum, the handler's constructor must set the following values defined by the `Log` base class:

```
$this->_id = md5(microtime().rand());
$this->_name = $name;
$this->_ident = $ident;
$this->_mask = Log::UPTO($level);
```

The [Handler Methods](#handler-methods) section below details the various standard methods that can be implemented by a log handler. The [Utility Methods](#utility-methods) section describes some useful utility methods provided by the `Log` base class which may be useful when implementing a log handler.

### [6.3 Extending Existing Handlers](#id86)

[](#63extending-existing-handlers)

Extending existing handlers is very similar to [writing new handlers](#writing-new-handlers) with the exception that, instead of inheriting from the `Log` base class directly, the handler extends an existing handler's class. This is a useful way of adding some custom behavior to an existing handler without writing an entirely new class (in the spirit of object-oriented programming).

For example, [the mail handler](#the-mail-handler) could be extended to support sending messages with MIME-encoded attachments simply by authoring a new `Log_mail_mime`class with a compliant constructor and a custom `log()` method. The rest of the standard methods would fall back on the `Log_mail` base class's implementations.

Obviously, the specific details involved in extending an existing handler require a good working understanding of that handler's implementation.

### [6.4 Handler Methods](#id87)

[](#64handler-methods)

#### [6.4.1 bool open()](#id88)

[](#641bool-open)

The `open()` method is called to open the log resource for output. Handlers can call `open()` immediately upon construction or lazily at runtime (perhaps when the first log event is received).

The `Log` base class provides a protected `$_opened` member variable which should be set to `true` when the log handler is opened and `false` when it is closed. Handler methods can inspect this value to determine whether or not the handler is currently open and ready for output.

If the `open()` method fails to ready the handler for output, it should return `false` and set `$this->_opened` to `false`.

#### [6.4.2 bool close()](#id89)

[](#642bool-close)

The `close()` method is called to close the log resource. This method is the analog of the `open()` method. It should be safe to call `close()`even when the handler is not open for output.

If the `close()` method fails to close the handler, it should return `false`. Otherwise, it should return `true`. The `$this->_opened`flag should also be updated appropriately.

#### [6.4.3 bool flush()](#id90)

[](#643bool-flush)

The `flush()` method flushes any buffered log events, as described in [Flushing Log Events](#flushing-log-events). The implementation of this method will be largely handler-specific. If the handler does not support buffered output, implementing this method is not necessary; the `Log` class's `flush()`method will be called instead.

#### [6.4.4 bool log($message, $priority = null)](#id91)

[](#644bool-logmessage-priority--null)

The `log()` method is the core of every log handler. It is called whenever the user wishes to log an event. The implementation of this method is very handler-specific. It should return `true` or `false`, depending on whether or not the message was successfully logged by the handler.

The `log()` implementation should be sure to call [\_announce()](#void-announce-event) whenever an event is successfully logged.

### [6.5 Utility Methods](#id92)

[](#65utility-methods)

These utility methods are provided by the `Log` base class and provide common, useful functionality to handler implementations.

#### [6.5.1 string \_extractMessage($message)](#id93)

[](#651string-_extractmessagemessage)

This method returns the string representation of the provided message data.

If `$message` is an object, `_extractMessage()` will attempt to extract the message text using a known method (such as a [PEAR\_Error](http://pear.php.net/manual/en/core.pear.pear-error.php) object's [getMessage()](http://pear.php.net/manual/en/core.pear.pear-error.getmessage.php) method). If a known method, cannot be found, the serialized representation of the object will be returned.

If the message data is already a string, it will be returned unchanged.

#### [6.5.2 string \_format($format, $timestamp, $priority, $message)](#id94)

[](#652string-_formatformat-timestamp-priority-message)

This method produces a formatted log line based on a format string and a set of [tokens](#log-line-format) representing the current log record and state.

#### [6.5.3 bool \_isMasked($priority)](#id95)

[](#653bool-_ismaskedpriority)

This method checks if the given priority is included in the handler's current level mask. This is useful for determining whether or not a log event should be written to the handler's log.

#### [6.5.4 void \_announce($event)](#id96)

[](#654void-_announceevent)

This method informs any registered [log observers](#log-observers) that a new event has been logged. `$event` is an array containing two named elements:

```
array('priority' => $priority, 'message' => $message)
```

`_announce()` should be called from a handler's [log()](#bool-log-message-priority-null) method whenever an event is successfully logged. Otherwise, registered observers will never become aware of the event.

###  Health Score

33

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 95.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~326 days

Total

5

Last Release

2966d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/683012?v=4)[Ben Plessinger](/maintainers/plessbd)[@plessbd](https://github.com/plessbd)

---

Top Contributors

[![jparise](https://avatars.githubusercontent.com/u/10311?v=4)](https://github.com/jparise "jparise (395 commits)")[![stigsb](https://avatars.githubusercontent.com/u/169939?v=4)](https://github.com/stigsb "stigsb (4 commits)")[![derrabus](https://avatars.githubusercontent.com/u/1506493?v=4)](https://github.com/derrabus "derrabus (4 commits)")[![tvvcox](https://avatars.githubusercontent.com/u/743820?v=4)](https://github.com/tvvcox "tvvcox (2 commits)")[![mj](https://avatars.githubusercontent.com/u/5277?v=4)](https://github.com/mj "mj (2 commits)")[![till](https://avatars.githubusercontent.com/u/27003?v=4)](https://github.com/till "till (2 commits)")[![CloCkWeRX](https://avatars.githubusercontent.com/u/365751?v=4)](https://github.com/CloCkWeRX "CloCkWeRX (2 commits)")[![derickr](https://avatars.githubusercontent.com/u/208074?v=4)](https://github.com/derickr "derickr (1 commits)")[![fzerorubigd](https://avatars.githubusercontent.com/u/935155?v=4)](https://github.com/fzerorubigd "fzerorubigd (1 commits)")[![tabacco](https://avatars.githubusercontent.com/u/102973?v=4)](https://github.com/tabacco "tabacco (1 commits)")[![smgallo](https://avatars.githubusercontent.com/u/2301909?v=4)](https://github.com/smgallo "smgallo (1 commits)")

---

Tags

loglogging

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ubccr-log/health.svg)

```
[![Health](https://phpackages.com/badges/ubccr-log/health.svg)](https://phpackages.com/packages/ubccr-log)
```

###  Alternatives

[monolog/monolog

Sends your logs to files, sockets, inboxes, databases and various web services

21.4k949.6M6.2k](/packages/monolog-monolog)[symfony/monolog-bundle

Symfony MonologBundle

2.9k244.8M1.4k](/packages/symfony-monolog-bundle)[sentry/sentry

PHP SDK for Sentry (http://sentry.io)

1.9k221.1M236](/packages/sentry-sentry)[sentry/sentry-laravel

Laravel SDK for Sentry (https://sentry.io)

1.3k110.7M122](/packages/sentry-sentry-laravel)[rap2hpoutre/laravel-log-viewer

A Laravel log reader

3.2k14.4M65](/packages/rap2hpoutre-laravel-log-viewer)[sentry/sdk

This is a meta package of sentry/sentry. We recommend using sentry/sentry directly.

327133.3M138](/packages/sentry-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
