我刚开始使用Laravel,发现每当我们得到任何错误/异常时,Laravel本身就会在日志文件中追加堆栈跟踪结果。
有没有办法停止它,因为我根本不需要它,它会不必要地增加生产服务器上的日志文件大小。
请帮我摆脱这个问题。提前感谢!!
是-你可以用这样的东西覆盖App::error()
过滤器:
App::error(function(Exception $exception, $code)
{
Log::error('This is the only error message that will appear in your logs');
if( ! (Config::get('app.debug')))
{
return Response::view('errors.error_page', array(), 500);
}
});
覆盖app/Exceptions/Handler.php
中的报告()。
这是我在我的项目中使用的。
use IlluminateSupportFacadesLog;
public function report(Exception $exception)
{
// parent::report($exception);
if ($this->shouldntReport($exception)) {
return;
}
// Remove stack-trace when not debugging.
if (!config('app.debug')) {
Log::error(
sprintf(
"nr%s: %s in %s:%dnr",
get_class($exception),
$exception->getMessage(),
$exception->getFile(),
$exception->getLine()
)
);
// 'trace' => $exception->getTraceAsString(),
}
}
我将APP_DEBUG=false
投入生产。
有人可能会发现这很有用,所以这里是我的贡献。我是这样处理这个问题的。
首先,我创建了一个名为logAnException
的辅助函数,用于每当我想处理try-catch
的异常时,例如
try {
// do some work
return redirect()->back();
}
catch (Exception $exception) {
// USAGE EXAMPLE
logAnException($exception);
return redirect()->back()->withInput( $request->except('_token') );
}
logAnException
看起来像这样…
function logAnException(Exception $exception) {
$exceptionFormat = "nAppName-EXCEPTION nMESSAGE:: %s nFILE:: %s nLINE::%s nn";
IlluminateSupportFacadesLog::info(sprintf($exceptionFormat,
// some exceptions don't come with a message
!empty(trim($exception->getMessage()))
? $exception->getMessage()
: get_class($exception),
$exception->getFile(),
$exception->getLine()
));
}
Laravel中的错误记录可以在AppExceptionsHandler
类的report
方法中被覆盖。所以,我只是用logAnException($exception);
代替了传统的parent::report($exception);
,像这样
public function report(Exception $exception)
{
// parent::report($exception);
logAnException($exception);
}
这样,异常现在只需要5行就可以呈现了。