Laravel框架 之 日志和错误

本文的示例代码参考log & bugsnag

目录

  • 日志

  • 错误

日志

composer create-project laravel/laravel log --prefer-dist "5.5.*"
# cd log
vim routes/web.php
echo "APP_LOG=daily" >> .env
  • 测试
php artisan serve
curl localhost:8000 # 返回"index"
cat $(find storage/logs -name "[0-9a-zA-Z]*" | tail -n1)
[2018-04-27 09:29:23] local.INFO: This is some useful information.
[2018-04-27 09:29:23] local.WARNING: Something could be going wrong.
[2018-04-27 09:29:23] local.ERROR: Something is really going wrong.
#Linux
sed -i "s/APP_LOG_LEVEL=debug/APP_LOG_LEVEL=warning/g" .env

# MacOS
sed -i "" "s/APP_LOG_LEVEL=debug/APP_LOG_LEVEL=warning/g" .env
  • 测试
# 更新.env配置后服务需要重启生效
php artisan serve
rm storage/logs/*.log

curl localhost:8000 # 返回"index"
cat $(find storage/logs -name "[0-9a-zA-Z]*" | tail -n1)
[2018-04-27 09:36:31] local.WARNING: Something could be going wrong.
[2018-04-27 09:36:31] local.ERROR: Something is really going wrong.

错误

composer create-project laravel/laravel bugsnag --prefer-dist "5.5.*"

注意

错误处理在app/Exceptions/Handler.php文件中

cat app/Exceptions/Handler.php| tail -25
    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }
}

其中

在report函数中将错误上报到第三方错误统计平台中

在render函数中处理异常渲染HTTP响应

下面

我们将以第三方错误统计平台Bugsnag为例 来看一下错误处理的效果

# cd bugsnag
composer require "bugsnag/bugsnag-laravel:^2.0"
vim config/app.php
return [
    'providers' => [
        /*
         * Package Service Providers...
         */
        Bugsnag\BugsnagLaravel\BugsnagServiceProvider::class,
    ],
];
echo "BUGSNAG_API_KEY=***" >> .env

这里的BUGSNAG_API_KEY是在Bugsnag注册后得到的

vim app/Providers/AppServiceProvider.php
app->alias('bugsnag.logger', \Illuminate\Contracts\Logging\Log::class);
        $this->app->alias('bugsnag.logger', \Psr\Log\LoggerInterface::class);
    }
}
vim routes/web.php
  • 测试
php artisan serve
curl localhost:8000 # 返回"index"

此时 打开bugsnag管理后台可以看到错误报告如下

Laravel框架 之 日志和错误_第1张图片
error-reporting-01.png

参考

  • 错误与日志

你可能感兴趣的:(Laravel框架 之 日志和错误)