Monolog in Silex application

1.1k views Asked by At

I try to use Monolog in my Silex application, according to the doc

http://silex.sensiolabs.org/doc/master/providers/monolog.html

I declare MonologServiceProvider in the app.php file as follow:

use Silex\Provider\MonologServiceProvider;

$app->register(new MonologServiceProvider(), array(
    'monolog.logfile' => __DIR__ . '/../files/logs/log.log',
));

And I try to write in my log.log file on the controler:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// In a controler
$app['monolog']->info("test");
$app['monolog']->debug("test");
$app['monolog']->warning("test");
$app['monolog']->error("test");

I don't have any error, but it is not working at all.

I just wan't to put my "test" message in my log.log file, how can I do that ?

Thanks for help

1

There are 1 answers

0
Adam Cameron On

I can't really answer your question based on the info you've given, but it's a slow-news day here, so strummed-up a working Silex site with working logging. All the files are on Github, but I'll repeat them here for ease of reading.

composer.json

{
    "require" : {
        "silex/silex" : "^2.0",
        "monolog/monolog" : "^1.0"
    },
    "autoload" : {
        "psr-4" : {
            "community\\" : "src/"
        }
    }
}

public/index.php

<?php

use \community\app\Application;

require_once realpath(__DIR__ . '/../vendor/autoload.php');

$app = new Application();
$app["debug"] = true;
$app->run();

src/app/Application.php

<?php

namespace community\app;

use \Silex\Application as SilexApplication;
use Silex\Provider\MonologServiceProvider;

class Application extends SilexApplication {

    function __construct() {

        parent::__construct();
        $this->registerServices();
        $this->mountControllers();
    }

    function registerServices(){
        $this->register(new MonologServiceProvider(), [
            "monolog.logfile" => realpath(__DIR__ . "/../../log") . "/general.log"
        ]);
    }

    function mountControllers() {
        $this->get('/testLog', 'community\controller\TestLogController::doGet');
    }

}

src/controller/TestLogController.php

<?php

namespace community\controller;

use community\app\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class TestLogController {

    public function doGet(Request $request, Application $app) {

        $app["monolog"]->info("hi!");

        return new Response("All good", Response::HTTP_OK);
    }
}

That writes to log/general.log as follows:

[2016-12-28 13:58:05] app.INFO: hi! [] []

One thing I noticed is that if the path to the log file is bung, then Monolog just seems to swallow it (which is not exactly ideal). This could well be your issue.

Anyway, grab the code above and mess around with it. Hopefully you'll be able to work out the differences between yours and mine, and get yours working.