Readouble

Laravel 5.2 エラーとログ

イントロダクション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'

dailyログモードを使用する場合、Laravelはデフォルトで5日分のログのみ残します。保存する日数を調整したい場合は、app.php設定ファイルへlog_max_files設定値を追加してください。When using the daily log mode, Laravel will only retain five days of log files by default. If you want to adjust the number of retained files, you may add an optional log_max_files configuration value to your app.php configuration file:

'log_max_files' => 30

カスタム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;

Laravelはデフォルトで全ログレベルを書き出します。実働環境では、このデフォルトログレベルを変更することが多いでしょう。app.php設定ファイルへlog_levelオプション値を付け加えてください。Laravelは指定されたレベル以上をログします。例えば、log_levelerrorにすれば、errorcriticalalertemergencyメッセージがログされます。By default, Laravel writes all log levels. In your production environment, you may wish to configure the default log level by adding the log_level option to your app.php configuration file. Laravel will then log all levels greater than or equal to the specified severity level. For example, a default log_level of error will log error, critical, alert, and emergency messages:

'log_level' => env('APP_LOG_LEVEL', 'debug'),

例外ハンドラThe Exception Handler

全例外はApp\Exceptions\Handlerクラスで処理されます。このクラスはreportrender二つのメソッドで構成されています。両メソッドの詳細を見ていきましょう。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メソッドは例外をログするか、BugSnagSentryのような外部サービスに送信するために使います。デフォルト状態のreportメソッドは、ただ渡された例外をベースクラスに渡し、そこで例外はログされます。しかし好きなように例外をログすることが可能です。The report method is used to log exceptions or send them to an external service like BugSnag[https://bugsnag.com] or Sentry[https://github.com/getsentry/sentry-laravel]. 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, 'Unauthorized action.');

このメソッドはリクエストのライフサイクル中であればいつでも使用できます。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 a log file for your application 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で定義されているemergencyalertcriticalerrorwarningnoticeinfodebugの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('User failed to login.', ['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();

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作