Commit 2153e86d authored by Dave Marshall's avatar Dave Marshall

Multiple Monolog Loggers Cookbook

parent fd3ba62d
......@@ -14,6 +14,7 @@ The cookbook section contains recipes for solving specific problems.
validator_yaml
sub_requests
error_handler
multiple_loggers
Recipes
-------
......@@ -35,3 +36,5 @@ Recipes
* :doc:`How to make sub-requests <sub_requests>`.
* :doc:`How to convert errors to exceptions <error_handler>`.
* :doc:`How to use multiple monolog loggers <multiple_loggers>`.
Using multiple monolog loggers
==============================
Having separate instances of `Monolog` for different parts of your system is
often desirable and allows you to configure them independantly, allowing for fine
grained control of where your logging goes and in what detail.
This simple example allows you to quickly configure several monolog instances,
using the bundled handler, but each with a different channel.
.. code-block:: php
$app['monolog.factory'] = $app->protect(function ($name) use ($app) {
$log = new $app['monolog.logger.class']($name);
$log->pushHandler($app['monolog.handler']);
return $log;
});
foreach (array('auth', 'payments', 'stats') as $channel) {
$app['monolog.'.$channel] = $app->share(function ($app) use ($channel) {
return $app['monolog.factory']($channel);
});
}
As your application grows, or your logging needs for certain areas of the
system become apparent, it should be straightforward to then configure that
particular service separately, including your customisations.
.. code-block:: php
$app['monolog.payments'] = $app->share(function ($app) {
$log = new $app['monolog.logger.class']('payments');
$handler = new StreamHandler($app['monolog.payments.logfile'], $app['monolog.payment.level']);
$log->pushHandler($handler);
return $log;
});
Alternatively, you could attempt to make the factory more complicated, and rely
on some conventions.
.. code-block:: php
$app['monolog.factory'] = $app->protect(function ($name) use ($app) {
$log = new $app['monolog.logger.class']($name);
$handlers = isset($app['monolog.'.$name.'handlers'])
? $app['monolog.'.$name.'handlers']
: array($app['monolog.handler']);
foreach ($handlers as $handler) {
$log->pushHandler($handler);
}
return $log;
});
$app['monolog.payments.handlers'] = $app->share(function ($app) {
return array(
new \Monolog\Handler\StreamHandler(__DIR__.'/../payments.log', \Monolog\Logger::DEBUG),
);
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment