How to log exceptions with matching line breaks using Monolog with Slim 3?
$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 gone wrong!");
};
};
$container['phpErrorHandler'] = function ($container) {
return $container['errorHandler'];
};
When any exception is thrown, I get one line in the error log. Maybe my memory is going fuzzy, but the PHP error log by default will format things on multiple lines ...
Is there a way to format it nicely? Or I will 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.
+3
source to share
2 answers
This is the Formatter Monologue option and Slim doesn't talk about it.
The way to do it nicely is to use Formatters in MonoLog.
The default formatting is LineFormatter
public function __construct($format = null, $dateFormat = null, $allowInlineLineBreaks = false, $ignoreEmptyContextAndExtra = false)
As you can see the third parameter $allowInlineLineBreaks
, so you can set it 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);
+2
source to share
Here's a job using regex:
$traceStrings = preg_split(
"/(#\d+)/",
$exception->getTraceAsString(),
null,
PREG_SPLIT_DELIM_CAPTURE
);
/** @var \Monolog\Logger $monoLog */
$monoLog = $container->logger;
$monoLog->addError($exception->getMessage());
$monoLog->addError($exception->getTraceAsString());
foreach ($traceStrings as $ts)
$monoLog->addError($ts);
$monoLog->addError($exception->getFile());
$monoLog->addError($exception->getCode());
$monoLog->addError($exception->getLine());
0
source to share