Readouble

Laravel master エラーとログ

イントロダクションIntroduction

新しいLaravelプロジェクトを開始する時点で、エラーと例外の処理は既に設定済みです。App\Exceptions\Handlerクラスはアプリケーションで発生する全例外をログし、ユーザへ表示するためのクラスです。このドキュメントでは、このクラスの詳細を確認していきます。When you start a new Laravel project, error and exception handling is already configured for you. The App\Exceptions\Handler class is where all exceptions triggered by your application are logged and then rendered back to the user. We'll dive deeper into this class throughout this documentation.

パワフルで様々なログハンドラをサポートしているMonologをLaravelはログに利用しています。単一ログファイルへのログ、一定期間ごとのログファイル切り替え、システムログへのエラー情報の書き込みを選べるように、Laravelはハンドラをあらかじめ準備しています。For logging, Laravel utilizes the Monolog[https://github.com/Seldaek/monolog] library, which provides support for a variety of powerful log handlers. Laravel configures several of these handlers for you, allowing you to choose between a single log file, rotating log files, or writing error information to the system log.

設定Configuration

エラー詳細Error Detail

アプリケーションエラー発生時にユーザに対し表示する詳細の表示量は、config/app.php設定ファイルのdebug設定オプションで決定します。デフォルト状態でこの設定オプションは、.envファイルで指定されるAPP_DEBUG環境変数の値を反映します。The debug option in your config/app.php configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG environment variable, which is stored in your .env file.

local環境ではAPP_DEBUG環境変数をtrueに設定すべきでしょう。実働環境ではこの値をいつもfalseにすべきです。実働環境でこの値をtrueにしてしまうと、アプリケーションのエンドユーザへ、セキュリティリスクになりえる設定情報を表示するリスクを犯すことになります。For local development, you should set the APP_DEBUG environment variable to true. In your production environment, this value should always be false. If the value is set to true in production, you risk exposing sensitive configuration values to your application's end users.

ログストレージLog Storage

Laravelはデフォルトで、単一ファイル(single)、日別ファイル(daily)、 システムログ(syslog)、エラーログ(errorlog)ログモードへのログ情報書き込みをサポートしています。Laravelが使用するストレージ機構の設定は、config/app.php設定ファイルのlogオプションを変更します。たとえば単一ファイルではなく、日別のログファイルを使用したい場合、app設定ファイルのlogの値に、dailyを設定してください。Out of the box, Laravel supports writing log information to single files, daily files, the syslog, and the errorlog. To configure which storage mechanism Laravel uses, you should modify the log option in your config/app.php configuration file. For example, if you wish to use daily log files instead of a single file, you should set the log value in your app configuration file to daily:

'log' => 'daily'

日別ログファイルの最大数Maximum Daily Log Files

dailyログモード使用時にLaravelはデフォルトで、5日分のログファイルだけを残します。保存しておくファイルの数を調整したいときは、app設定ファイルの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 a log_max_files configuration value to your app configuration file:

'log_max_files' => 30

ログレベルLog Severity Levels

Monologでは、異なった重大さのレベルのログを扱えます。Laravelはデフォルトで全ログレベルをストレージに書き込みます。しかし、実働環境ではapp.php設定ファイルのlog_levelオプションへ、ログすべき最低の重大さレベルを指定したいことでしょう。When using Monolog, log messages may have different levels of severity. By default, Laravel writes all log levels to storage. However, in your production environment, you may wish to configure the minimum severity that should be logged by adding the log_level option to your app.php configuration file.

このオプションを一度設定すると、Laravelは指定された重大さ以上の全レベルをログします。たとえば、log_levelerrorを設定すると、errorcriticalalertemergencyメッセージがログされます。Once this option has been configured, Laravel will log all levels greater than or equal to the specified severity. For example, a default log_level of error will log error, critical, alert, and emergency messages:

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

lightbulb">Tip!! Monologは以下の重大さレベルを取り扱います:debuginfonoticewarningerrorcriticalalertemergency{tip} Monolog recognizes the following severity levels - from least severe to most severe: debug, info, notice, warning, error, critical, alert, emergency.

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

reportメソッドThe Report Method

全例外はApp\Exceptions\Handlerクラスで処理されます。このクラスはreportrender二つのメソッドで構成されています。両メソッドの詳細を見ていきましょう。reportメソッドは例外をログするか、BugSnagSentryのような外部サービスに送信するために使います。デフォルト状態のreportメソッドは、ただ渡された例外をベースクラスに渡し、そこで例外はログされます。しかし好きなように例外をログすることが可能です。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. 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  $exception
 * @return void
 */
public function report(Exception $exception)
{
    if ($exception instanceof CustomException) {
        //
    }

    return parent::report($exception);
}

タイプによる例外の無視Ignoring Exceptions By Type

例外ハンドラの$dontReportプロパティーは、ログしない例外のタイプの配列で構成します。たとえば、404エラー例外と同様に、他のタイプの例外もログしたくない場合です。必要に応じてこの配列へ、他の例外を付け加えてください。The $dontReport property of the exception handler contains an array of exception types that will not be logged. For example, exceptions resulting from 404 errors, as well as several other types of errors, are not written to your log files. You may add other exception types to this array as needed:

/**
 * レポートしない例外のリスト
 *
 * @var array
 */
protected $dontReport = [
    \Illuminate\Auth\AuthenticationException::class,
    \Illuminate\Auth\Access\AuthorizationException::class,
    \Symfony\Component\HttpKernel\Exception\HttpException::class,
    \Illuminate\Database\Eloquent\ModelNotFoundException::class,
    \Illuminate\Validation\ValidationException::class,
];

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  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($exception instanceof CustomException) {
        return response()->view('errors.custom', [], 500);
    }

    return parent::render($request, $exception);
}

HTTP例外HTTP Exceptions

例外の中にはサーバでのHTTPエラーコードを表しているものがあります。たとえば「ページが見つかりません」エラー(404)や「未認証エラー」(401)、開発者が生成した500エラーなどです。アプリケーションのどこからでもこの種のレスポンスを生成するには、abortヘルパを使用します。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, you may use the abort helper:

abort(404);

abortヘルパは即座に例外を発生させ、その例外は例外ハンドラによりレンダーされることになります。オプションとしてレスポンスのテキストを指定することもできます。The abort helper will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:

abort(403, 'Unauthorized action.');

カスタムHTTPエラーページCustom HTTP Error Pages

様々なHTTPステータスコードごとに、Laravelはカスタムエラーページを簡単に返せます。たとえば404 HTTPステータスコードに対してカスタムエラーページを返したければ、resources/views/errors/404.blade.phpを作成してください。このファイルはアプリケーションで起こされる全404エラーに対し動作します。ビューはこのディレクトリに置かれ、対応するHTTPコードと一致した名前にしなくてはなりません。abortヘルパが生成するHttpExceptionインスタンスは、$exception変数として渡されます。Laravel makes it easy to display 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. The views within this directory should be named to match the HTTP status code they correspond to. The HttpException instance raised by the abort function will be passed to the view as an $exception variable.

ログLogging

Laravelのログ機能は、強力なMonologライブラリーのシンプルな上位レイヤーを提供します。Laravelはデフォルトで、アプリケーションの日別ログファイルをstorage/logsディレクトリへ作成するように設定されています。ログへ情報を書き込むにはLogファサードを使います。Laravel provides a simple abstraction 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 App\User;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 指定ユーザーのプロフィールを表示
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id)
    {
        Log::info('ユーザのプロフィール表示。 ID:'.$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($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);

コンテキストデータ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!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作