[英]How do I log exceptions with appropriate linebreaks 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'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... 也许我的记忆很模糊,但默认的PHP错误记录会在多行上很好地格式化...
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. 即使有上述情况,迹线也会显示为单行。
This is a Monolog Formatter setting and Slim has no say in this. 这是一个Monolog Formatter设置,Slim在此没有发言权。
The way to do this nicely is use a Formatters in MonoLog. 很好地做到这一点的方法是在MonoLog中使用Formatters。
The default formatter is the LineFormatter 默认格式化程序是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. 如您所见,第三个参数是$allowInlineLineBreaks
因此您可以将其设置为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);
Here is a work around 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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.