Question

In my Slim framework application I would like to be able to send log message to the console where I run the PHP builtin web server:

php -S localhost:8000 -c /etc/php5/apache2/php.ini-development).

I am using the monolog logger:

// index.php
$app->container->singleton('log', function () {
  $log = new \Monolog\Logger('myapp');
  $log->pushHandler(new \Monolog\Handler\StreamHandler('../logs/app.log', \Monolog\Logger::DEBUG));
  return $log;
});

How do I do that?

Was it helpful?

Solution

You can use error_log with a message_type set to 4 and it will output to the SAPI logging handler:

error_log('testing', 4);

It will output in this style:

$ php -S localhost:8000 test.php
PHP 5.4.20 Development Server started at Wed Jan 22 21:09:35 2014
Listening on http://localhost:8000
Document root is /home/David
Press Ctrl-C to quit.
[Wed Jan 22 21:09:52 2014] testing

Monolog also supports this message type using the ErrorLogHandler class. Example:

require 'vendor/autoload.php';

use Monolog\Logger;
use Monolog\Handler\ErrorLogHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new ErrorLogHandler(ErrorLogHandler::SAPI, Logger::WARNING));

// add records to the log
$log->addWarning('Foo');
$log->addError('Bar');

And the logged output for this:

$ php -S localhost:8000 test.php
PHP 5.4.20 Development Server started at Wed Jan 22 21:18:02 2014
Listening on http://localhost:8000
Document root is /home/David/testing
Press Ctrl-C to quit.
[Wed Jan 22 21:18:06 2014] [2014-01-22 21:18:06] name.WARNING: Foo [] []

[Wed Jan 22 21:18:06 2014] [2014-01-22 21:18:06] name.ERROR: Bar [] []

Not quite sure why the monolog version includes the timestamp twice, however.

You can conditionally set which logger to use by checking the php_sapi_name() function:

if (php_sapi_name() == 'cli-server') {
    /* configure monolog with the ErrorLogHandler */
} else {
    /* configure monolog with the StreamHandler */
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top