2017-07-17 40 views
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's gone wrong!"); 
    }; 
}; 

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

當發生異常時,我會在錯誤日誌中看到一行。也許我的記憶是模糊的,但默認的PHP錯誤日誌會很好地格式化多行的東西...如何使用Monolog和Slim 3合適的換行符記錄異常?

有沒有一種方法來很好地格式化?

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

即使有微量上面出現一行:還是我必須使用類似手動格式化。

回答

0

這裏是一個工作使用正則表達式周圍:

$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()); 
2

這是一個獨白格式化設置和斯利姆沒有發言權在此。

很好地做到這一點的方法是在MonoLog中使用格式化程序。

默認格式是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);