o2-kng
Last Updated: September 20, 2017
·
15.35K
· malteo
D19108207d7ebfd0e18e4a7108c5d656

How to use Monolog in any PHP file

If you have to debug code inside an old PHP project which doesn't use some Composer-like goodness, or a spaghetti code single PHP file (urgh!), you could find Monolog (https://github.com/Seldaek/monolog) useful.

Here's how to plug it inside any PHP file:

<?php

spl_autoload_register(function ($class) {
  $file = $__DIR__.'/relative/path/to/Monolog/src/'.strtr($class, '\\', '/').'.php';
  if (file_exists($file)) {
    require $file;
    return true;
  }
});

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

$log = new Logger('name');
$log->pushHandler(new StreamHandler(__DIR__.'/path/to/your.log', Logger::DEBUG));

$log->addInfo('Do your magic here.');
Say Thanks
Respond

3 Responses
Add your response

3290

Hello,
with the same code I have :
PHP Fatal error: Interface 'Psr\Log\LoggerInterface' not found in /var/www/tests/monolog-master/src/Monolog/Logger.php on line 28

over 1 year ago ·
9709
Ad8731d1f51a8ee333e45cb1e70c3ca4

@laurent_guigo

For this example, you will need to do something like:


splautoloadregister(function ($class) {
$file = $DIR.'/relative/path/to/psr/log/'.strtr($class, '\', '/').'.php';
if (file_exists($file)) {
require $file;
return true;
}
});
</pre>
over 1 year ago ·
29306

Simple but very useful. Thanks!

3 months ago ·