Q:

Logging full stack trace with Monolog

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?

A:

Actually since version 1.12.0 it is possible to include stacktrace at your log file: there is new method of LineFormatter called includeStacktraces.
To use this, you need to overwrite default behaviour of monolog formatter:
config.yml
monolog:
    handlers:
        main:
            formatter: your.monolog.service.id
            (rest of config is as usual)

services.yml
services:
    your.monolog.service.id:
        class: Monolog\Formatter\LineFormatter
        calls:
            - [includeStacktraces]

Check github for more info:
Pull request

A:

I have a very simple solution!!!
$mylogger->error((string) $exception);

A:

No, You cannot log the stack trace using the built-in formatters.  See my question here.
If you take a look at LineFormatter.php you see that the normalizeException method is responsible for grabbing the exception data. So, I had to create a new formatter that extended LineFormatter.  Here's the code:
<?php

namespace Monolog\Formatter;

use Exception;

class ExceptionLineFormatter extends LineFormatter
{
    protected function normalizeException(Exception $e)
    {
        return 'Message: ' . $e->getMessage() . 
                'Stack Trace: '. $e->getTraceAsString();
    }
}

And I initialized my logger like so:
$logFile = 'MyLogFile.txt';
$handler = new StreamHandler($logFile);
$handler->setFormatter(new ExceptionLineFormatter);
$log = new Logger('MyLogger');
$handler = self::getStreamHander();
$log->pushHandler($handler);

This will will print out your stack trace.

