如何使用Monolog with Slim 3使用适当的换行符记录异常?

时间:2017-07-17 15:16:04

标签: 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'];
};

当发生异常时,我在错误日志中得到一行。也许我的记忆很模糊,但默认的PHP错误记录会在多行上很好地格式化...

有没有办法很好地格式化它?或者我是否使用以下内容手动格式化:

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

即使使用上述内容,迹线也会显示为单行。

2 个答案:

答案 0 :(得分:2)

这是Monolog Formatter设置,Slim对此没有发言权。

很好地做到这一点的方法是在MonoLog中使用Formatters。

默认格式化程序是LineFormatter

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

正如您所看到的,第三个参数是$allowInlineLineBreaks,因此您可以将其设置为true。 例如:

$handler = new Monolog\Handler\StreamHandler($settings['path'], $settings['level']);
$lineFormatter = new \Monolog\Formatter\LineFormatter(null, null, true);
$handler->setFormatter($lineFormatter);
$logger->pushHandler($handler);

答案 1 :(得分:0)

这是一个使用正则表达式的工作:

Wanted but not invoked:
careGroupService.fetchTimeZones();
-> at com.example.api.test 
.restcontroller.EmployeeRestControllerUnitTest 
.testFetchTimezones(EmployeeRestControllerUnitTest.java:73)
Actually, there were zero interactions with this mock.