Last Updated: September 09, 2019
·
23.51K
· malteo

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.');

3 Responses
Add your response

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 ·

@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 ·

Simple but very useful. Thanks!

over 1 year ago ·