Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I log exceptions with appropriate linebreaks using Monolog with Slim 3?

Tags:

php

slim

monolog

$container['logger'] = function (\Slim\Container $c) {
    $settings = $c->get('settings')['logger'];
    $logger = new Monolog\Logger($settings['name']);
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
    return $logger;
};

$container['errorHandler'] = function (\Slim\Container $container) {
    return function (\Slim\Http\Request $request, \Slim\Http\Response $response, \Exception $exception) use ($container) {
        /** @var \Monolog\Logger $monoLog */
        $monoLog = $container->logger;
        $monoLog->addError((string)$exception);

        $response->getBody()->rewind();
        return $response->withStatus(500)
            ->withHeader('Content-Type', 'text/html')
            ->write("Oops, something's gone wrong!");
    };
};

$container['phpErrorHandler'] = function ($container) {
    return $container['errorHandler'];
};

When ever an exception occurs I get a single line in the error log. Perhaps my memory is going fuzzy but the default PHP error logging would format things nicely on multiple lines...

Is there a way to format it nicely? Or do I have manually format it using something like:

    $monoLog->addError($exception->getMessage());
    $monoLog->addError($exception->getTraceAsString());
    $monoLog->addError($exception->getFile());
    $monoLog->addError($exception->getCode());
    $monoLog->addError($exception->getLine());

Even with the above the trace appears as a single line.

like image 904
Chris Stryczynski Avatar asked Dec 19 '25 16:12

Chris Stryczynski


1 Answers

This is a Monolog Formatter setting and Slim has no say in this.

The way to do this nicely is use a Formatters in MonoLog.

The default formatter is the LineFormatter

public function __construct($format = null, $dateFormat = null, $allowInlineLineBreaks = false, $ignoreEmptyContextAndExtra = false)

As you can see the third parameter is $allowInlineLineBreaks so you can set that to true. For example:

$handler = new Monolog\Handler\StreamHandler($settings['path'], $settings['level']);
$lineFormatter = new \Monolog\Formatter\LineFormatter(null, null, true);
$handler->setFormatter($lineFormatter);
$logger->pushHandler($handler);
like image 78
Timmetje Avatar answered Dec 22 '25 05:12

Timmetje



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!