Package Home

Zend Framework 2 Documentation (Manual)

PHK Home

File: /_sources/modules/zend.log.writers.txt

Size:8110
Storage flags:no_autoload,compress/gzip (32%)

.. _zend.log.writers:

Writers
=======

A Writer is an object that inherits from ``Zend\Log\Writer\AbstractWriter``. A Writer's responsibility is to record
log data to a storage backend.

.. _zend.log.writers.stream:

Writing to Streams
------------------

``Zend\Log\Writer\Stream`` sends log data to a `PHP stream`_.

To write log data to the *PHP* output buffer, use the URL ``php://output``. Alternatively, you can send log data
directly to a stream like ``STDERR`` (``php://stderr``).

.. code-block:: php
   :linenos:

   $writer = new Zend\Log\Writer\Stream('php://output');
   $logger = new Zend\Log\Logger();
   $logger->addWriter($writer);

   $logger->info('Informational message');

To write data to a file, use one of the `Filesystem URLs`_:

.. code-block:: php
   :linenos:

   $writer = new Zend\Log\Writer\Stream('/path/to/logfile');
   $logger = new Zend\Log\Logger();
   $logger->addWriter($writer);

   $logger->info('Informational message');

By default, the stream opens in the append mode ("a"). To open it with a different mode, the
``Zend\Log\Writer\Stream`` constructor accepts an optional second parameter for the mode.

The constructor of ``Zend\Log\Writer\Stream`` also accepts an existing stream resource:

.. code-block:: php
   :linenos:

   $stream = @fopen('/path/to/logfile', 'a', false);
   if (! $stream) {
       throw new Exception('Failed to open stream');
   }

   $writer = new Zend\Log\Writer\Stream($stream);
   $logger = new Zend\Log\Logger();
   $logger->addWriter($writer);

   $logger->info('Informational message');

You cannot specify the mode for existing stream resources. Doing so causes a ``Zend\Log\Exception`` to be thrown.

.. _zend.log.writers.database:

Writing to Databases
--------------------

``Zend\Log\Writer\Db`` writes log information to a database table using ``Zend\Db\Adapter\Adapter``. The
constructor of ``Zend\Log\Writer\Db`` receives a ``Zend\Db\Adapter\Adapter`` instance, a table name, an optional
mapping of event data to database columns, and an optional string contains the character separator for the log
array:

.. code-block:: php
   :linenos:

   $dbconfig = array(
       // Sqlite Configuration
       'driver' => 'Pdo',
       'dsn' => 'sqlite:' . __DIR__ . '/tmp/sqlite.db',
   );
   $db = new Zend\Db\Adapter\Adapter($dbconfig);

   $writer = new Zend\Log\Writer\Db($db, 'log_table_name');
   $logger = new Zend\Log\Logger();
   $logger->addWriter($writer);

   $logger->info('Informational message');

The example above writes a single row of log data to the database table named 'log_table_name' table. The database
column will be created according to the event array generated by the ``Zend\Log\Logger`` instance.

If we specify the mapping of the events with the database columns the log will store in the database only the
selected fields.

.. code-block:: php
   :linenos:

   $dbconfig = array(
       // Sqlite Configuration
       'driver' => 'Pdo',
       'dsn' => 'sqlite:' . __DIR__ . '/tmp/sqlite.db',
   );
   $db = new Zend\Db\Adapter\Adapter($dbconfig);

   $mapping = array(
       'timestamp' => 'date',
       'priority'  => 'type',
       'message'   => 'event'
   );
   $writer = new Zend\Log\Writer\Db($db, 'log_table_name', $mapping);
   $logger = new Zend\Log\Logger();
   $logger->addWriter($writer);

   $logger->info('Informational message');

The previous example will store only the log information timestamp, priority and message in the database fields
date, type and event.

The ``Zend\Log\Writer\Db`` has a fourth optional parameter in the constructor. This parameter is the character
separator for the log events managed by an array. For instance, if we have a log that contains an array extra
fields, this will be translated in 'extra-field', where '-' is the character separator (default) and field is the
subname of the specific extra field.

.. _zend.log.writers.firephp:

Writing to FirePHP
------------------

``Zend\Log\Writer\FirePHP`` writes log information to the  `FirePHP`_ Firefox extension. In order to use this you have
to install the FirePHPCore Server Library and the FirePHP browser extension.

To install the FirePHPCore Library you can use composer. Add the repository and the required line to your topmost composer.json:

.. code-block:: json
   :linenos:

   {
      [ .. ]


      "repositories": [{
         "type" : "pear",
         "url" : "pear.firephp.org",
         "vendor-alias" : "firephp"
      }],
      "minimum-stability": "dev",
      "require" : {
         [ ... ]
         "firephp/FirePHPCore" : "*"
      }
   }

.. _zend.log.writers.chromephp

Writing to ChromePHP
--------------------

``Zend\Log\Writer\ChromePHP`` sends log data to the `ChromePHP`_ Chrome extension`.

To use the ChromePHP writer, you will also need to include the `ChromePHP Library`_ library in your application include path.
The easiest way to do this is to include the library in your composer.json file.

.. code-block:: json
  :linenos

  {
      [ .. ]

      "require" : {
          [ ... ]
          "ccampbell/chromephp": "4.1.0"
      }
  }

.. _zend.log.writers.mail

Writing to Mail
---------------

.. _zend.log.writers.mongodb

Writing to MongoDB
------------------

.. _zend.log.writers.syslog

Writing to Syslog
-----------------

.. _zend.log.writers.zendmonitor

Writing to Zend Monitor
-----------------------

.. _zend.log.writers.null:

Stubbing Out the Writer
-----------------------

The ``Zend\Log\Writer\Noop`` is a stub that does not write log data to anything. It is useful for disabling logging
or stubbing out logging during tests:

.. code-block:: php
   :linenos:

   $writer = new Zend\Log\Writer\Noop;
   $logger = new Zend\Log\Logger();
   $logger->addWriter($writer);

   // goes nowhere
   $logger->info('Informational message');

Migration from 2.0-2.3 to 2.4+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Version 2.4 adds support for PHP 7. In PHP 7, ``null`` is a reserved keyword,
which required renaming the ``Null`` log writer. If you were using the ``Null`` writer
directly previously, you will now receive an ``E_USER_DEPRECATED`` notice on
instantiation. Please update your code to refer to the ``Noop`` class instead.

Users pulling their ``Null`` writer instance from the writer plugin manager
receive a ``Noop`` instance instead starting in 2.4.0.

.. _zend.log.writers.mock:

Testing with the Mock
---------------------

The ``Zend\Log\Writer\Mock`` is a very simple writer that records the raw data it receives in an array exposed as a
public property.

.. code-block:: php
   :linenos:

   $mock = new Zend\Log\Writer\Mock;
   $logger = new Zend\Log\Logger();
   $logger->addWriter($mock);

   $logger->info('Informational message');

   var_dump($mock->events[0]);

   // Array
   // (
   //    [timestamp] => 2007-04-06T07:16:37-07:00
   //    [message] => Informational message
   //    [priority] => 6
   //    [priorityName] => INFO
   // )

To clear the events logged by the mock, simply set ``$mock->events = array()``.

.. _zend.log.writers.compositing:

Compositing Writers
-------------------

There is no composite Writer object. However, a Log instance can write to any number of Writers. To do this, use
the ``addWriter()`` method:

.. code-block:: php
   :linenos:

   $writer1 = new Zend\Log\Writer\Stream('/path/to/first/logfile');
   $writer2 = new Zend\Log\Writer\Stream('/path/to/second/logfile');

   $logger = new Zend\Log\Logger();
   $logger->addWriter($writer1);
   $logger->addWriter($writer2);

   // goes to both writers
   $logger->info('Informational message');

You can also specify the priority number for each writer to change the order of writing. The priority number is an
integer number (greater or equal to 1) passed as second parameter in the ``addWriter()`` method.



.. _`PHP stream`: http://www.php.net/stream
.. _`Filesystem URLs`: http://www.php.net/manual/en/wrappers.php#wrappers.file
.. _`FirePHP`: http://www.firephp.org/
.. _`ChromePHP`: https://chrome.google.com/webstore/detail/chrome-logger/noaneddfkdjfnfdakjjmocngnfkfehhd
.. _`ChromePHP Library`: http://craig.is/writing/chrome-logger

For more information about the PHK package format: http://phk.tekwire.net