イントロダクション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のログは「チャンネル」に基づいています。各チャンネルは、ログ情報を書き込む特定の方法を表します。たとえば、single
チャンネルはログファイルを単一のログファイルに書き込みますが、slack
チャンネルはログメッセージをSlackへ送信します。ログメッセージは、重大度に基づいて複数のチャンネルに書き込まれる場合があります。Laravel logging is based on
"channels". Each channel represents a
specific way of writing log information. For
example, the single
channel writes log
files to a single log file, while the
slack
channel sends log messages to
Slack. Log messages may be written to multiple
channels based on their severity.
内部的に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 options
for your application's logging behavior 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をproduction
やlocal
など、現在の環境に一致する「チャンネル名」でインスタンス化します。この値を変更するには、チャンネルの構成に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
各ログチャンネルは「ドライバ」によって駆動されます。ドライバは、ログメッセージが実際に記録される方法と場所を決定します。以下のログチャンネルドライバは、すべてのLaravelアプリケーションで利用できます。これらのドライバのほとんどのエントリは、アプリケーションのconfig/logging.php
設定ファイルに予め用意しているため、このファイルを確認して内容をよく理解してください。Each log channel is powered by a
"driver". The driver determines how and
where the log message is actually recorded. The
following log channel drivers are available in every
Laravel application. An entry for most of these
drivers is already present in your application's
config/logging.php
configuration file,
so be sure to review this file to become familiar
with its contents:
名前Name | 説明Description |
---|---|
custom custom |
指定ファクトリを呼び出してチャンネルを作成するドライバA driver that calls a specified factory to create a channel |
daily daily |
日毎にファイルを切り替えるRotatingFileHandler ベースのMonologドライバA
RotatingFileHandler based
Monolog driver which rotates
daily |
errorlog errorlog |
ErrorLogHandler ベースのMonologドライバAn
ErrorLogHandler based
Monolog driver |
monolog monolog |
Monologがサポートしているハンドラを使用するMonologファクトリドライバA Monolog factory driver that may use any supported Monolog handler |
null null |
すべてのログメッセージを破棄するドライバA driver that discards all log messages |
papertrail papertrail |
SyslogUdpHandler ベースのMonologドライバA
SyslogUdpHandler based
Monolog driver |
single single |
単一のファイルまたはパスベースのロガーチャンネル(StreamHandler )A single file or path
based logger channel
(StreamHandler ) |
slack slack |
SlackWebhookHandler ベースのMonologドライバA
SlackWebhookHandler based
Monolog driver |
stack stack |
「マルチチャンネル」チャンネルの作成を容易にするラッパーA wrapper to facilitate creating "multi-channel" channels |
syslog syslog |
SyslogHandler ベースのMonologドライバA
SyslogHandler based Monolog
driver |
高度なチャンネルのカスタマイズのドキュメントをチェックして、
Note:monolog
およびcustom
ドライバの詳細を確認してください。Note
Check out the documentation on advanced channel customization[#monolog-channel-customization] to learn more about themonolog
andcustom
drivers.
チャンネルの事前設定Channel Prerequisites
singleチャンネルとdailyチャンネルの設定Configuring The Single and Daily Channels
single
チャンネルとdaily
チャンネルは、bubble
、permission
、locking
の3オプションの設定オプションがあります。The single
and
daily
channels have three optional
configuration options: bubble
,
permission
, and
locking
.
名前Name | 説明Description | デフォルトDefault |
---|---|---|
bubble bubble |
メッセージが処理された後、他のチャンネルにバブルアップする必要があるかを示すIndicates if messages should bubble up to other channels after being handled | true true |
locking locking |
ログファイルに書き込む前に、ログファイルのロックを試みるかを示すAttempt to lock the log file before writing to it | false false |
permission permission |
ログファイルのパーミッションThe log file's permissions | 0644 0644 |
さらに、daily
チャンネルの保存ポリシーは、days
オプションで設定できます。Additionally, the retention
policy for the daily
channel can be
configured via the days
option:
名前Name | 説明Description | デフォルトDefault |
---|---|---|
days days |
デイリーログファイルを保持する日数The number of days that daily log files should be retained | 7 7 |
Papertrailチャンネルの設定Configuring The Papertrail Channel
papertrail
チャンネルには、host
およびport
設定オプションが必要です。これらの値は、Papertrailから取得できます。The papertrail
channel requires the host
and
port
configuration options. You can
obtain these values from
Papertrail[https://help.papertrailapp.com/kb/configuration/configuring-centralized-logging-from-php-apps/#send-events-from-php-app].
Slackチャンネルの設定Configuring The Slack Channel
slack
チャンネルにはurl
設定オプションが必要です。このURLは、皆さんのSlackチーム用に設定した受信Webフックのの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.
デフォルトでは、Slackはcritical
レベル以上のログのみ受信します。ただしconfig/logging.php
設定ファイルで、Slackログチャンネルの設定配列内のlevel
設定オプションを変更することで調整できます。By default, Slack will only
receive logs at the critical
level and
above; however, you can adjust this in your
config/logging.php
configuration file
by modifying the level
configuration
option within your Slack log channel's configuration
array.
廃止ワーニングのログLogging Deprecation Warnings
PHPやLaravelなどのライブラリは、その機能の一部が非推奨となり、将来のバージョンで削除されることをユーザーに通知することがよくあります。これらの非推奨の警告をログに残したい場合は、アプリケーションのconfig/logging.php
設定ファイルで、お好きなdeprecations
ログチャンネルを指定できます。PHP, Laravel, and other libraries
often notify their users that some of their features
have been deprecated and will be removed in a future
version. If you would like to log these deprecation
warnings, you may specify your preferred
deprecations
log channel in your
application's config/logging.php
configuration file:
'deprecations' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'channels' => [
...
]
あるいは、deprecations
という名前のログチャンネルを定義することもできます。この名前のログチャンネルが存在する場合、常にdeprecationsのログを記録するために使用されます。Or, you may define a log channel
named deprecations
. If a log channel
with this name exists, it will always be used to log
deprecations:
'channels' => [
'deprecations' => [
'driver' => 'single',
'path' => storage_path('logs/php-deprecation-warnings.log'),
],
],
ログスタックの構築Building Log Stacks
前述のように、stack
ドライバを使用すると、便利に複数のチャンネルを1つのログチャンネルに組み合わせることができます。ログスタックの使用方法を説明するために、本番アプリケーションで使われる可能性のある構成例を見てみましょう。As mentioned previously, the
stack
driver allows you to combine
multiple channels into a single log channel for
convenience. 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
オプションを介して他の2つのチャンネルsyslog
とslack
を集約している点に注目してください。したがって、メッセージをログに記録するとき、これらのチャンネルの両方にメッセージをログに記録する機会があります。ただし、以降で説明するように、これらのチャンネルが実際にメッセージをログに記録するかどうかは、メッセージの重大度/「レベル」によって決定されます。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. However, as we will see below,
whether these channels actually log the message may
be determined by the message's severity /
"level".
ログレベルLog Levels
上記の例のsyslog
およびslack
チャンネル設定に存在するlevel
設定オプションに注意してください。このオプションは、チャンネルによってログに記録されるためにメッセージが必要とする最小の「レベル」を決定します。Laravelのログサービスを強化するMonologは、RFC5424仕様で定義されているすべてのログレベルを提供しています。これらのログレベルは、重要度の高い順に、emergency、alert、critical、error、warning、notice、info、debugです。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].
In descending order of severity, these log levels
are: 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
メッセージをログに記録すると、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
ファサードを使用してログに情報を書き込むことができます。前述のように、ロガーはRFC5424仕様で定義されている8つのログレベルを提供しますemergency、alert、critical、error、warning、notice、info、debug)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:
use Illuminate\Support\Facades\Log;
Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);
これらのメソッドのいずれかを呼び出して、対応するレベルのメッセージをログに記録できます。デフォルトでは、メッセージはlogging
設定ファイル中に設定しているデフォルトのログチャンネルに書き込まれます。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
logging
configuration file:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Log;
class UserController extends Controller
{
/**
* 特定のユーザーのプロファイルの表示
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
Log::info('Showing the user profile for user: '.$id);
return view('user.profile', [
'user' => User::findOrFail($id)
]);
}
}
コンテキスト情報Contextual Information
コンテキストデータの配列をlogメソッドへ渡せます。このコンテキストデータはフォーマットされ、ログメッセージとともに表示されます。An array of contextual data may be passed to the log methods. This contextual data will be formatted and displayed with the log message:
use Illuminate\Support\Facades\Log;
Log::info('User failed to login.', ['id' => $user->id]);
特定のチャンネルで、後に続くすべてのログエントリに含まれるコンテキスト情報を指定したい場合もあるでしょう。例えば、アプリケーションに入ってくる各リクエストに関連付けたリクエストIDをログに記録したい場合があります。これを行うには、Log
ファサードのwithContext
メソッドを呼び出します。Occasionally, you may wish to
specify some contextual information that should be
included with all subsequent log entries in a
particular channel. For example, you may wish to log
a request ID that is associated with each incoming
request to your application. To accomplish this, you
may call the Log
facade's
withContext
method:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class AssignRequestId
{
/**
* 受信リクエストの処理
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$requestId = (string) Str::uuid();
Log::withContext([
'request-id' => $requestId
]);
return $next($request)->header('Request-Id', $requestId);
}
}
もし、すべてのログ収集チャンネルでコンテキスト情報を共有したい場合は、Log::shareContext()
メソッドを呼び出してください。このメソッドは、作成したすべてのチャンネルと、以降に作成するすべてのチャンネルへ、コンテキスト情報を提供します。通常、shareContext
メソッドは、アプリケーションサービスプロバイダのboot
メソッドから呼び出すべきでしょう。If you would like to share
contextual information across all logging
channels, you may call the
Log::shareContext()
method. This method
will provide the contextual information to all
created channels and any channels that are created
subsequently. Typically, the
shareContext
method should be called
from the boot
method of an application
service provider:
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class AppServiceProvider
{
/**
* 全アプリケーションサービスの初期起動処理
*
* @return void
*/
public function boot()
{
Log::shareContext([
'invocation-id' => (string) Str::uuid(),
]);
}
}
特定チャンネルへの書き込み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:
use Illuminate\Support\Facades\Log;
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!');
オンデマンドチャンネルOn-Demand Channels
アプリケーションの logging
設定ファイルに設定を用意しなくても、実行時に構成を指定することにより、オンデマンドチャンネルを作成することも可能です。そのためには、設定の配列をLog
ファサードのbuild
メソッドに渡してください。It is also possible to create an
on-demand channel by providing the configuration at
runtime without that configuration being present in
your application's logging
configuration file. To accomplish this, you may pass
a configuration array to the Log
facade's build
method:
use Illuminate\Support\Facades\Log;
Log::build([
'driver' => 'single',
'path' => storage_path('logs/custom.log'),
])->info('Something happened!');
オンデマンドチャンネルをオンデマンドログスタックに含めたい場合もあるでしょう。これを実現するには、stack
メソッドに渡す配列へオンデマンドチャンネルのインスタンスを含めます。You may also wish to include an
on-demand channel in an on-demand logging stack.
This can be achieved by including your on-demand
channel instance in the array passed to the
stack
method:
use Illuminate\Support\Facades\Log;
$channel = Log::build([
'driver' => 'single',
'path' => storage_path('logs/custom.log'),
]);
Log::stack(['slack', $channel])->info('Something happened!');
monologチャンネルカスタマイズMonolog Channel Customization
チャンネル向けMonologカスタマイズCustomizing Monolog For Channels
場合によっては、既存のチャンネルに対してMonologを設定する方法を完全に制御する必要が起きます。たとえば、Laravelの組み込みのsingle
チャンネル用にカスタム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
Laravel's built-in single
channel.
このためには、チャンネルの設定で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. There is
no conventional location where these classes should
be placed, so you are free to create a directory
within your application to contain these
classes:
'single' => [
'driver' => 'single',
'tap' => [App\Logging\CustomizeFormatter::class],
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
チャンネルでtap
オプションを設定したら、Monologインスタンスをカスタマイズするクラスを定義する準備が整います。このクラスに必要なメソッドは1つだけです。__invoke
はIlluminate\Log\Logger
インスタンスを受け取ります。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;
use Monolog\Formatter\LineFormatter;
class CustomizeFormatter
{
/**
* 指定するロガーインスタンスをカスタマイズ
*
* @param \Illuminate\Log\Logger $logger
* @return void
*/
public function __invoke($logger)
{
foreach ($logger->getHandlers() as $handler) {
$handler->setFormatter(new LineFormatter(
'[�tetime%] %channel%.%level_name%: %message% %context% %extra%'
));
}
}
}
サービスコンテナによって解決されるため、必要なコンストラクターの依存関係は自動的に依存注入されます。Note
Note:すべての「tap」クラスは
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にはさまざまな利用可能なハンドラがあり、Laravelはそれぞれに対する組み込みチャンネルを用意していません。場合によっては、対応するLaravelログドライバを持たない特定のMonologハンドラの単なるインスタンスであるカスタムチャンネルを作成したい場合があります。これらのチャンネルは、monolog
ドライバを使用して簡単に作成できます。Monolog has a variety of
available
handlers[https://github.com/Seldaek/monolog/tree/main/src/Monolog/Handler]
and Laravel does not include a built-in channel for
each one. In some cases, you may wish to create a
custom channel that is merely an instance of a
specific Monolog handler that does not have a
corresponding Laravel log driver. These channels can
be easily created using the monolog
driver.
monolog
ドライバを使用する場合、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 with
configuration option:
'logentries' => [
'driver' => 'monolog',
'handler' => Monolog\Handler\SyslogUdpHandler::class,
'with' => [
'host' => 'my.logentries.internal.datahubhost.company.com',
'port' => '10000',
],
],
MonologフォーマッターMonolog Formatters
monolog
ドライバを使用する場合、MonologLineFormatter
がデフォルトのフォーマッターとして使用されます。ただし、formatter
およびformatter_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 Custom 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 that contains the
name of the factory class which will be invoked to
create the Monolog instance:
'channels' => [
'example-custom-channel' => [
'driver' => 'custom',
'via' => App\Logging\CreateCustomLogger::class,
],
],
custom
ドライバチャンネルを設定したら、Monologインスタンスを作成するクラスを定義する準備が整います。このクラスには、Monologロガーインスタンスを返す単一の__invoke
メソッドのみが必要です。このメソッドは、チャンネル設定配列を唯一の引数として受け取ります。Once you have configured the
custom
driver channel, you're ready to
define the class that will create your Monolog
instance. This class only needs a single
__invoke
method which should return the
Monolog logger instance. The method will receive the
channels configuration array as its only
argument:
<?php
namespace App\Logging;
use Monolog\Logger;
class CreateCustomLogger
{
/**
* カスタムMonologインスタンスの生成
*
* @param array $config
* @return \Monolog\Logger
*/
public function __invoke(array $config)
{
return new Logger(/* ... */);
}
}