Readouble

Laravel 5.7 ログ

イントロダクションIntroduction

アプリケーションで発生している事象を確実に捕らえられるように、Laravelはログメッセージをファイルやシステムエラーログ、さらにチーム全体に知らせるためのSlack通知も可能な、堅牢なログサービスを提供しています。To help you learn more about what's happening within your application, Laravel provides robust logging services that allow you to log messages to files, the system error log, and even to Slack to notify your entire team.

そのために、Laravelは多くのパワフルなログハンドラをサポートしている、Monologライブラリーを活用しています。Laravelはそうしたハンドラの設定を簡単にできるようにし、アプリケーションのログ処理に合わせカスタマイズするため、ハンドラを多重に使ったり、マッチングできるようにしています。Under the hood, Laravel utilizes the Monolog[https://github.com/Seldaek/monolog] library, which provides support for a variety of powerful log handlers. Laravel makes it a cinch to configure these handlers, allowing you to mix and match them to customize your application's log handling.

設定Configuration

アプリケーションのログシステムの設定はすべて、config/logging.php設定ファイルに用意されています。このファイルはアプリケーションのログチャンネルを設定できるため、使用可能なチャンネルやその他のオプションをしっかりとレビューしてください。よく使用されるオプションを以降からレビューします。All of the configuration for your application's logging system is housed in the config/logging.php configuration file. This file allows you to configure your application's log channels, so be sure to review each of the available channels and their options. We'll review a few common options below.

デフォルトでは、Laravelはstackチャンネルをメッセージをログする場合に使用します。stackチャンネルは、複数のログチャンネルを一つのログチャンネルへ集結するために使用します。スタックの構築に関する詳細は、このドキュメントで後ほど説明します。By default, Laravel will use the stack channel when logging messages. The stack channel is used to aggregate multiple log channels into a single channel. For more information on building stacks, check out the documentation below[#building-log-stacks].

チャンネル名の設定Configuring The Channel Name

Monologはデフォルトでproductionlocalのような、現在の環境と一致する「チャンネル名」でインスタンス化されます。この値を変更するには、チャンネルの設定にnameオプションを追加してください。By default, Monolog is instantiated with a "channel name" that matches the current environment, such as production or local. To change this value, add a name option to your channel's configuration:

'stack' => [
    'driver' => 'stack',
    'name' => 'channel-name',
    'channels' => ['single', 'slack'],
],

利用可能なチャンネルドライバAvailable Channel Drivers

名前Name 説明Description
stackstack 「マルチチャンネル」チャンネルを作成するためのラッパー機能A wrapper to facilitate creating "multi-channel" channels
singlesingle シングルファイル/パスベースのロガーチャンネル(StreamHandlerA single file or path based logger channel (StreamHandler)
dailydaily RotatingFileHandlerベースの毎日ファイルを切り替えるMonologドライバA RotatingFileHandler based Monolog driver which rotates daily
slackslack SlackWebhookHandlerベースのMonologドライバA SlackWebhookHandler based Monolog driver
syslogsyslog SyslogHandlerベースのMonologドライバA SyslogHandler based Monolog driver
errorlogerrorlog ErrorLogHandlerベースのMonologドライバA ErrorLogHandler based Monolog driver
monologmonolog サポートしているMonologハンドラをどれでも使用できる、MonologファクトリドライバA Monolog factory driver that may use any supported Monolog handler
customcustom チャンネルを生成するため、指定したファクトリを呼び出すドライバA driver that calls a specified factory to create a channel

lightbulb">Tip!! monologcustomドライバの詳細は、上級チャンネルカスタマイズのドキュメントを確認し、学んでください。{tip} Check out the documentation on advanced channel customization[#advanced-monolog-channel-customization] to learn more about the monolog and custom drivers.

シングルファイルとディリーチャンネルの設定Configuring The Single and Daily Channels

singledailyチャンネルは3つ設定オプションを持っています。bubblepermissionlockingです。The single and daily channels have three optional configuration options: bubble, permission, and locking.

名前Name 説明Description デフォルト値Default
bubblebubble 処理後に他のチャンネルへメッセージをバブルアップさせるかIndicates if messages should bubble up to other channels after being handled truetrue
permissionpermission ログファイルのパーミッションThe log file's permissions 644644
lockinglocking 書き込む前にログファイルのロックを試みるAttempt to lock the log file before writing to it falsefalse

Slackチャンネルの設定Configuring The Slack Channel

slackチャンネルには、url設定オプションが必須です。このURLはSlackチームに対して設定されている、incoming webhookへのURLと一致させる必要があります。The slack channel requires a url configuration option. This URL should match a URL for an incoming webhook[https://slack.com/apps/A0F7XDUAZ-incoming-webhooks] that you have configured for your Slack team.

ログスタックの構築Building Log Stacks

先に説明した通り、stackドライバーは、複数のチャンネルを一つのログチャンネルへまとめるために使用します。ログスタックの使用方法を説明するため、ある実働環境に対する設定例を見てみましょう。As previously mentioned, the stack driver allows you to combine multiple channels into a single log channel. To illustrate how to use log stacks, let's take a look at an example configuration that you might see in a production application:

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['syslog', 'slack'],
    ],

    'syslog' => [
        'driver' => 'syslog',
        'level' => 'debug',
    ],

    'slack' => [
        'driver' => 'slack',
        'url' => env('LOG_SLACK_WEBHOOK_URL'),
        'username' => 'Laravel Log',
        'emoji' => ':boom:',
        'level' => 'critical',
    ],
],

では、個別にこの設定を確認しましょう。最初に、stackチャンネルがchannelsオプションによりsyslogslack、2つのチャンネルをまとめていることに注目してください。Let's dissect this configuration. First, notice our stack channel aggregates two other channels via its channels option: syslog and slack. So, when logging messages, both of these channels will have the opportunity to log the message.

ログレベルLog Levels

上記の例で、syslogslackチャンネル設定の中に、level設定オプションが存在していることに注目です。このオプションは、そのチャンネルでメッセージをログする、最低の「レベル」を定めるオプションです。Laravelのログサービスを動かしているMonologは、RFC 5424規約で定められている全ログレベルが使用できます。emergencyalertcriticalerrorwarningnoticeinfodebugです。Take note of the level configuration option present on the syslog and slack channel configurations in the example above. This option determines the minimum "level" a message must be in order to be logged by the channel. Monolog, which powers Laravel's logging services, offers all of the log levels defined in the RFC 5424 specification[https://tools.ietf.org/html/rfc5424]: emergency, alert, critical, error, warning, notice, info, and debug.

debugメソッドを使用し、メッセージをログしてみることを想像しましょう。So, imagine we log a message using the debug method:

Log::debug('An informational message.');

上記設定では、syslogチャンネルにより、システムログへメッセージを書き込みます。しかしながら、エラーメッセージはcritical以上ではないため、Slackには送られません。ところが、emergencyメッセージをログする場合、両方のチャンネルに対する最低の基準レベル以上のため、システムログとSlackの両方へ送られます。Given our configuration, the syslog channel will write the message to the system log; however, since the error message is not critical or above, it will not be sent to Slack. However, if we log an emergency message, it will be sent to both the system log and Slack since the emergency level is above our minimum level threshold for both channels:

Log::emergency('The system is down!');

ログメッセージの記述Writing Log Messages

Logファサードを使い、情報をログできます。先に説明したように、ロガーはRFC 5424規約に定義されている、emergencyalertcriticalerrorwarningnoticeinfodebugの8ログレベルを提供しています。You may write information to the logs using the Log facade[/docs/{{version}}/facades]. As previously mentioned, the logger provides the eight logging levels defined in the RFC 5424 specification[https://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);

ログメッセージレベルに応じたメソッドを呼び出してください。デフォルトでは、config/logging.php設定ファイルで定義されているデフォルトログチャンネルへ、メッセージが書き込まれます。So, you may call any of these methods to log a message for the corresponding level. By default, the message will be written to the default log channel as configured by your config/logging.php configuration file:

<?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('Showing user profile for user: '.$id);

        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

文脈情報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]);

指定チャンネルへの記述Writing To Specific Channels

アプリケーションのデフォルトチャンネルの代わりに、別のチャンネルへメッセージをログしたい場合もあります。設定ファイルに定義してあるチャンネルをLogファサードのchannelメソッドを使い取得し、ログしてください。Sometimes you may wish to log a message to a channel other than your application's default channel. You may use the channel method on the Log facade to retrieve and log to any channel defined in your configuration file:

Log::channel('slack')->info('Something happened!');

複数チャンネルで構成されたログスタックをオンデマンドで生成したい場合は、stackメソッドを使います。If you would like to create an on-demand logging stack consisting of multiple channels, you may use the stack method:

Log::stack(['single', 'slack'])->info('Something happened!');

Monologチャンネルの上級カスタマイズAdvanced Monolog Channel Customization

チャンネル用MonologカスタマイズCustomizing Monolog For Channels

既存チャンネルに対するMonologの設定方法を複雑にコントロールする必要がある場合もあり得ます。たとえば、指定したチャンネルハンドラに対し、MonologのFormatterInterfaceカスタム実装を設定したい場合です。Sometimes you may need complete control over how Monolog is configured for an existing channel. For example, you may want to configure a custom Monolog FormatterInterface implementation for a given channel's handlers.

そのためには、チャンネルの設定で、tap配列を定義します。tap配列は、生成された後のMonologインスタンスをカスタマイズ(もしくは利用 : "tap into")する機会を与える、クラスのリストを含んでいる必要があります。To get started, define a tap array on the channel's configuration. The tap array should contain a list of classes that should have an opportunity to customize (or "tap" into) the Monolog instance after it is created:

'single' => [
    'driver' => 'single',
    'tap' => [App\Logging\CustomizeFormatter::class],
    'path' => storage_path('logs/laravel.log'),
    'level' => 'debug',
],

チャンネルに対するtapオプションを定義したら、Monologインスタンスをカスタマイズするクラスを定義する準備が整いました。このクラスはIlluminate\Log\Loggerインスタンスを受け取る、__invokeメソッドのみ必要です。Illuminate\Log\Loggerインスタンスは、すべてのメソッドを裏で動作するMonologインスタンスへ送るプロキシクラスです。Once you have configured the tap option on your channel, you're ready to define the class that will customize your Monolog instance. This class only needs a single method: __invoke, which receives an Illuminate\Log\Logger instance. The Illuminate\Log\Logger instance proxies all method calls to the underlying Monolog instance:

<?php

namespace App\Logging;

class CustomizeFormatter
{
    /**
     * 渡されたロガーインスタンスのカスタマイズ
     *
     * @param  \Illuminate\Log\Logger  $logger
     * @return void
     */
    public function __invoke($logger)
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->setFormatter(...);
        }
    }
}

lightbulb">Tip!! すべての"tap"クラスは、サービスコンテナにより、依存解決されます。そのため、コンストラクタで要求した依存は、自動的に注入されます。{tip} All of your "tap" classes are resolved by the service container[/docs/{{version}}/container], so any constructor dependencies they require will automatically be injected.

Monologハンドラチャンネルの作成Creating Monolog Handler Channels

Monologはバラエティーに富んだ利用可能なハンドラを用意しています。あるケースでは、生成したいロガーのタイプが、単に特定のハンドラを持つMonologドライバであることがあります。こうしたチャンネルはmonologドライバーを使用し、生成できます。Monolog has a variety of available handlers[https://github.com/Seldaek/monolog/tree/master/src/Monolog/Handler]. In some cases, the type of logger you wish to create is merely a Monolog driver with an instance of a specific handler. These channels can be created using the monolog driver.

monologドライバーを使用する場合、インスタンス化するハンドラを指定するために、handler設定オプションを使います。任意のコンストラクタパラメータを指定する必要がある場合は、handler_with設定オプションを使用します。When using the monolog driver, the handler configuration option is used to specify which handler will be instantiated. Optionally, any constructor parameters the handler needs may be specified using the handler_with configuration option:

'logentries' => [
    'driver'  => 'monolog',
    'handler' => Monolog\Handler\SyslogUdpHandler::class,
    'handler_with' => [
        'host' => 'my.logentries.internal.datahubhost.company.com',
        'port' => '10000',
    ],
],

MonologフォーマッターMonolog Formatters

monologドライバーを使用する場合、Monolog LineFormatterをデフォルトフォーマッターとして使用します。しかし、フォーマッターのタイプをカスタマイズする必要がある場合は、formatterformatter_with設定オプションを使用します。When using the monolog driver, the Monolog LineFormatter will be used as the default formatter. However, you may customize the type of formatter passed to the handler using the formatter and formatter_with configuration options:

'browser' => [
    'driver' => 'monolog',
    'handler' => Monolog\Handler\BrowserConsoleHandler::class,
    'formatter' => Monolog\Formatter\HtmlFormatter::class,
    'formatter_with' => [
        'dateFormat' => 'Y-m-d',
    ],
],

Monologハンドラが提供する自身のフォーマッターを使用する場合は、formatter設定オプションにdefaultを値として指定してください。If you are using a Monolog handler that is capable of providing its own formatter, you may set the value of the formatter configuration option to default:

'newrelic' => [
    'driver' => 'monolog',
    'handler' => Monolog\Handler\NewRelicHandler::class,
    'formatter' => 'default',
],

ファクトリを用いたチャンネル生成Creating Channels Via Factories

Monologのインスタンス化と設定を完全にコントロールするために、完全なカスタムチャンネルを定義したい場合は、config/logging.php設定ファイルで、customドライバータイプを指定してください。Monologインスンタンスを生成するために、呼び出すファクトリクラスを指定するために、viaオプションを設定に含める必要があります。If you would like to define an entirely custom channel in which you have full control over Monolog's instantiation and configuration, you may specify a custom driver type in your config/logging.php configuration file. Your configuration should include a via option to point to the factory class which will be invoked to create the Monolog instance:

'channels' => [
    'custom' => [
        'driver' => 'custom',
        'via' => App\Logging\CreateCustomLogger::class,
    ],
],

customチャンネルを設定したら、Monologインスタンスを生成するクラスを定義する準備が整いました。このクラスはMonologインスタンスを返す、__invokeメソッドのみ必要です。Once you have configured the custom channel, you're ready to define the class that will create your Monolog instance. This class only needs a single method: __invoke, which should return the Monolog instance:

<?php

namespace App\Logging;

use Monolog\Logger;

class CreateCustomLogger
{
    /**
     * カスタムMonologインスタンスの生成
     *
     * @param  array  $config
     * @return \Monolog\Logger
     */
    public function __invoke(array $config)
    {
        return new Logger(...);
    }
}

章選択

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作