Logging full stack trace with Monolog

Viewed 39082

I use Monolog as a stand-alone library in my application and recently I ran into an issue. Let's say, at some point in my application I catch an exception and I want to log it:

$mylogger->error('Exception caught', array('exception' => $exception));

This works perfectly except one tiny thing - it doesn't log whole stack trace. Is it possible to log exception's full stack trace using monolog build-in formatters?

9 Answers

You can simply use the config file (Symfony Bundle) with the "include_stacktraces" parameter:

monolog:
    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: info
            channels: ["!event"]
            max_files: 10
            include_stacktraces: true <--- SET TO TRUE

@see this commit

@see the full schema (configuration)

Adding to Tomasz Madeyski's answer, this is how you can use it via code only:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\ErrorHandler;
use Monolog\Formatter\LineFormatter;

$formatter = new LineFormatter(LineFormatter::SIMPLE_FORMAT, LineFormatter::SIMPLE_DATE);
$formatter->includeStacktraces(true); // <--

$stream = new StreamHandler('error.log');
$stream->setFormatter($formatter);

$logger = new Logger('logger');
$logger->pushHandler($stream);

If you want to log stacktrace only when Exception is thrown, you can do this, in the AppServiceProvider:

public function register()
{
     $logger = Log::getMonolog();
     $logger->pushProcessor(function ($record) {
        if (isset($record['context']['exception']))
        {
            $record['extra']['stacktrace'] = $record['context']['exception']->getTraceAsString();
        }

        return $record;
    });
}

This will add the stacktrace to extra column, which then can be used per LineFormatter

Related