8

I am using the browser handler to log message into JS console

require_once 'vendor/autoload.php';

use Monolog\Logger;
use Monolog\Handler\BrowserConsoleHandler;

$log = new Logger('name');
$log->pushHandler(new BrowserConsoleHandler);

$data = array(1,2,3,4);

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

I am wondering, is it possible to log array such as $data into the console which reassemble the array content?

Ryan
  • 10,041
  • 27
  • 91
  • 156

3 Answers3

15

Try this:

$log->addWarning('Foo: ' . var_export($data, true));
benJ
  • 2,442
  • 1
  • 18
  • 16
  • Feel I should add, 5 years on from this answer, that the correct approach now is to use `$log->addWarning('Foo', $data);` as per Colin Smillie's answer, below. https://stackoverflow.com/a/39025294/2286736 – benJ Aug 09 '19 at 09:27
9

The best approach ( from the 2nd half of Felix's answer ) for an array is:

$log->addWarning('Foo:' , $data); 

The AddWarning will accept an array as the 2nd parameter and format it properly in the browser.

Using var_export will convert to a string and not format the array properly in the browser console.

Colin Smillie
  • 431
  • 3
  • 7
3

Also, you can try this:

$log->addWarning('Foo: ' . print_r($data, true));  

Or

$log->addWarning('Foo:' , $data);   
Félix Castro
  • 59
  • 1
  • 3