Configuring the Log extension

Nice comes with built-in integration with Monolog. This allows for PSR-3 compliant logging in your application.

The first step is requiring Monolog in your project. You can do this by updating your composer.json or running composer require at the command line.

  • Example composer.json:

    {
        "require": {
            "nice/framework": "~1.0",
            "monolog/monolog": "~1.11"
        }
    }

    The run composer update at the command line.

  • Using the composer command line tool

    composer require monolog/monolog:~1.11

With Monolog is installed, the next step is registering the LogExtension with your Nice Application.

use Nice\Extension\LogExtension;

// ...

$app = new Application();
$app->appendExtension(new LogExtension(array(
    'channels' => array(
        'default' => array(
            'handler' => 'stream',
            'level' => 100, // Debug
            'options' => array(
                'file' => '%app.log_dir%/dev.log'
            )
        )
    )
)));

With the above configuration, Nice will create the following service:

  • logger.default is an instance of Monolog\Logger, configured to write to the specified log file on any messages with level DEBUG or higher.

Tip: Check out Monolog documentation for more information on log levels and handlers.

Logger usage example

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Nice\Application;
use Nice\Router\RouteCollector;
use Nice\Extension\LogExtension;

$app = new Application();
$app->appendExtension(new LogExtension(array(
    'channels' => array(
        'default' => array(
            'handler' => 'stream',
            'level' => 100, // Debug
            'options' => array(
                'file' => '%app.log_dir%/main.log'
            )
        )
    )
)));

// Configure your routes
$app->set('routes', function (RouteCollector $r) {
    $r->map('/', 'home', function (Application $app, Request $request) {
        $app->get('logger.default')->debug('User hit the "home" action!');

        return new Response('Hello, world');
    });
});

Powered by Codex 1.1.0