イントロダクションIntroduction
新しいLaravelプロジェクトを開始する時点で、エラーと例外の処理は既に設定済みです。それに加えLaravelは、パワフルで様々なログハンドラーをサポートしているMonologログライブラリーと統合されています。When you start a new Laravel project, error and exception handling is already configured for you. In addition, Laravel is integrated with the Monolog[https://github.com/Seldaek/monolog] logging library, which provides support for a variety of powerful log handlers.
設定Configuration
エラーの詳細Error Detail
アプリケーションエラー発生時にブラウザに表示される詳細の表示量は、config/app.php設定ファイルのdebug設定オプションでコントロールします。デフォルト状態でこの設定オプションは、.envファイルで指定されるAPP_DEBUG環境変数の値を反映します。The amount of error detail your application displays through the browser is controlled by the debug configuration option in your config/app.php configuration file. By default, this configuration option is set to respect the APP_DEBUG environment variable, which is stored in your .env file.
local環境ではAPP_DEBUG環境変数をtrueに設定すべきでしょう。実働環境ではこの値をいつもfalseにすべきです。For local development, you should set the APP_DEBUG environment variable to true. In your production environment, this value should always be false.
ログモードLog Modes
Laravelは初めから単一ファイル(single)、日別ファイル(daily)、 システムログ(syslog)、エラーログ(errorlog)ログモードをサポートしています。たとえば単一ファイルにログする代わりに日別ログを取りたい場合は、config/app.php設定ファイルのlogをただ設定するだけです。Out of the box, Laravel supports single, daily, syslog and errorlog logging modes. For example, if you wish to use daily log files instead of a single file, you should simply set the log value in your config/app.php configuration file:
'log' => 'daily'
カスタムMonolog設定Custom Monolog Configuration
Monologがアプリケーションのために設定している内容を完全にコントロールしたければ、アプリケーションのconfigureMonologUsingメソッドを使ってください。このメソッドはbootstrap/app.phpファイルの中の$app変数が返される直前に呼びださなくてはなりません。If you would like to have complete control over how Monolog is configured for your application, you may use the application's configureMonologUsing method. You should place a call to this method in your bootstrap/app.php file right before the $app variable is returned by the file:
$app->configureMonologUsing(function($monolog) {
    $monolog->pushHandler(...);
});
return $app;
例外ハンドラーThe Exception Handler
全例外はApp\Exceptions\Handlerクラスで処理されます。このクラスはreportとrender二つのメソッドで構成されています。両メソッドの詳細を見ていきましょう。All exceptions are handled by the App\Exceptions\Handler class. This class contains two methods: report and render. We'll examine each of these methods in detail.
reportメソッドThe Report Method
reportメソッドは例外をログするか、BugSnagのような外部サービスに送信するために使います。デフォルト状態のreportメソッドは、ただ渡された例外をベースクラスに渡し、そこで例外はログされます。しかし好きなように例外をログすることが可能です。The report method is used to log exceptions or send them to an external service like BugSnag[https://bugsnag.com]. By default, the report method simply passes the exception to the base class where the exception is logged. However, you are free to log exceptions however you wish.
たとえば異なった例外を別々の方法レポートする必要がある場合、PHPのinstanceof比較演算子を使ってください。For example, if you need to report different types of exceptions in different ways, you may use the PHP instanceof comparison operator:
/**
 * 例外をログする
 *
 * ここは例外をSentryやBugsnagなどへ送るために良い場所
 *
 * @param  \Exception  $e
 * @return void
 */
public function report(Exception $e)
{
    if ($e instanceof CustomException) {
        //
    }
    return parent::report($e);
}
タイプによる例外の無視Ignoring Exceptions By Type
例外ハンドラーの$dontReportプロパティーは、ログしない例外のタイプの配列で構成します。デフォルトでは、404エラー例外はログされません。必要に応じてこの配列へ他の例外を付け加えてください。The $dontReport property of the exception handler contains an array of exception types that will not be logged. By default, exceptions resulting from 404 errors are not written to your log files. You may add other exception types to this array as needed.
renderメソッドThe Render Method
renderメソッドは与えられた例外をブラウザーに送り返すHHTPレスポンスへ変換することに責任を持っています。デフォルトで例外はベースクラスに渡され、そこでレスポンスが生成されます。しかし例外のタイプをチェックし、お好きなようにレスポンスを返してかまいません。The render method is responsible for converting a given exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you. However, you are free to check the exception type or return your own custom response:
/**
 * 例外をHTTPレスポンスへレンダー
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    if ($e instanceof CustomException) {
        return response()->view('errors.custom', [], 500);
    }
    return parent::render($request, $e);
}
HTTP例外HTTP Exceptions
例外の中にはサーバーでのHTTPエラーコードを表しているものがあります。たとえば「ページが見つかりません」エラー(404)や「未認証エラー」(401)、開発者が生成した500エラーなどです。アプリケーションのどこからでもこの種のレスポンスを生成するには、次のように実行します。Some exceptions describe HTTP error codes from the server. For example, this may be a "page not found" error (404), an "unauthorized error" (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, use the following:
abort(404);
abortメソッドは即座に例外を発生させ、その例外は例外ハンドラーによりレンダーされることになります。オプションとしてレスポンスのテキストを指定することもできます。The abort method will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:
abort(403, '許可されていないアクション');
このメソッドはリクエストのライフサイクル中であればいつでも使用できます。This method may be used at any time during the request's lifecycle.
カスタムHTTPエラーページCustom HTTP Error Pages
様々なHTTPステータスコードごとに、Laravelはカスタムエラーページを簡単に返せます。たとえば404 HTTPステータスコードに対してカスタムエラーページを返したければ、resources/views/errors/404.blade.phpを作成してください。このファイルはアプリケーションで起こされる全404エラーに対し動作します。Laravel makes it easy to return custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php. This file will be served on all 404 errors generated by your application.
ビューはこのディレクトリーに置かれ、対応するHTTPコードと一致した名前にしなくてはなりません。The views within this directory should be named to match the HTTP status code they correspond to.
ログLogging
Laravelのログ機能は、強力なMonologライブラリーのシンプルな上位レイヤーを提供しています。Laravelはデフォルトで、アプリケーションの日別ログファイルをstorage/logsディレクトリーへ作成するように設定されています。ログへ情報を書き込むにはLogファサードを使います。The Laravel logging facilities provide a simple layer on top of the powerful Monolog[http://github.com/seldaek/monolog] library. By default, Laravel is configured to create daily log files for your application which are stored in the storage/logs directory. You may write information to the logs using the Log facade[/docs/{{version}}/facades]:
<?php
namespace App\Http\Controllers;
use Log;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
    /**
     * 指定ユーザーのプロフィールを表示
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id)
    {
        Log::info('Showing user profile for user: '.$id);
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}
ログはRFC 5424で定義されているemergency、alert、critical、error、warning、notice、info 、debugの8レベルをサポートしています。The logger provides the eight logging levels defined in RFC 5424[http://tools.ietf.org/html/rfc5424]: emergency, alert, critical, error, warning, notice, info and debug.
Log::emergency($error);
Log::alert($error);
Log::critical($error);
Log::error($error);
Log::warning($error);
Log::notice($error);
Log::info($error);
Log::debug($error);
コンテキストデータContextual Information
ログメソッドにはコンテキストデータを配列で渡すこともできます。このコンテキストデータはログメッセージと一緒に整形され、表示されます。An array of contextual data may also be passed to the log methods. This contextual data will be formatted and displayed with the log message:
Log::info('ユーザーがログインに失敗。', ['id' => $user->id]);
裏で動作するMonologインスタンスへのアクセスAccessing The Underlying Monolog Instance
Monologはログに使用できる様々な追加のハンドラーを提供しています。必要であれば、Laravelが裏で使用しているMonologインスタンスへアクセスすることもできます。Monolog has a variety of additional handlers you may use for logging. If needed, you may access the underlying Monolog instance being used by Laravel:
$monolog = Log::getMonolog();