我有一个启用了调试的应用程序,转换为异常的错误和Monolog记录器服务:
ErrorHandler::register();
ExceptionHandler::register();
$app = new Silex\Application();
$logfile = dirname(__DIR__) . '/var/log/application.log';
$app->register(new Silex\Provider\MonologServiceProvider(), array(
'monolog.logfile' => $logfile,
'monolog.level' => Logger::DEBUG,
));
我想将错误记录到文件中,详见浏览器。
示例:我访问了一个不存在的URL,我在浏览器中收到了下两个错误:
2/2
Not NotFoundHttpException in RouterListener.php line 159:
No route found for "GET /xxx"
1. in RouterListener.php line 159
2. at RouterListener->onKernelRequest(object(GetResponseEvent), 'kernel.request', object(EventDispatcher))
3. at call_user_func(array(object(RouterListener), 'onKernelRequest'), object(GetResponseEvent), 'kernel.request', object(EventDispatcher)) in EventDispatcher.php line 164
...
1/2
ResourceNotFoundException in UrlMatcher.php line 102:
No routes found for "/xxx".
1. in UrlMatcher.php line 102
2. at UrlMatcher->match('/xxx') in RedirectableUrlMatcher.php line 30
3. at RedirectableUrlMatcher->match('/xxx') in LazyUrlMatcher.php line 51
...
但是唯一记录的文字是:
[2016-03-30 21:32:10] myapp.ERROR: Symfony\Component\HttpKernel\Exception\NotFoundHttpException: No route found for "GET /xxx" (uncaught exception) at ...route.../vendor/symfony/http-kernel/EventListener/RouterListener.php line 159 {"exception":"[object] (Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException(code: 0): No route found for \"GET /xxx\" at ...route.../vendor/symfony/http-kernel/EventListener/RouterListener.php:159, Symfony\\Component\\Routing\\Exception\\ResourceNotFoundException(code: 0): No routes found for \"/xxx\". at ...route.../vendor/symfony/routing/Matcher/UrlMatcher.php:102)"} []
[2016-03-30 21:32:10] myapp.INFO: < 404 [] []
有没有办法记录抛出的所有错误,包括完整的堆栈跟踪?
答案 0 :(得分:1)
您可以编写将格式化错误的日志格式化程序
配置monolog:
$logfile = dirname(__DIR__) . '/var/log/application.log';
$app->register(new Silex\Provider\MonologServiceProvider(), array(
'monolog.logfile' => $logfile,
'monolog.level' => Logger::DEBUG,
));
$app->extend('monolog', function($monolog, $app) {
static $initialized = false;
if ($initialized) return $monolog;
$initialized = true;
foreach ($monolog->getHandlers() as $handler)
if ($handler->getFormatter() instanceof \Monolog\Formatter\LineFormatter)
$handler->setFormatter(new \My\Formatter());
return $monolog;
});
格式化:
class \My\Formatter extends \Monolog\Formatter\NormalizerFormatter
{
public function format(array $record)
{
$output = ...;
return $output
}
public function formatBatch(array $records)
{
$output = ...;
return $output
}
}