log
- Write log message
- Write to the specified channel
- Customized Monolog channel Create channel through factory
Introduction
To help you understand more about what is happening in your application, Laravel provides a powerful logging service that allows you to record log messages, system error logs to files, and even use Slack notifications to your entire team.
In the Laravel framework, Laravel uses the Monolog library, which provides support for a variety of powerful log processing. Laravel makes it easy to configure these handlers, allowing you to mix and match them for custom application log processing.
Configuration
All application logging system configuration is located at
config/logging.php
in the configuration file. This file allows you to configure your application log channels, so be sure to review each available channel and their options. Of course, we'll review some of the commonly used options below.By default, Laravel will use
stack
to log messages. The stack channel is used to aggregate multiple log channels into a single channel. For more information about the stack, view the following documentation.Configure channel name
By default, Monolog is instantiated using a "channel name" that matches the current environment, such as
production
orlocal
. To change this value, add aname
option to your channel configuration:'stack' => [ 'driver' => 'stack', 'name' => 'channel-name', 'channels' => ['single', 'slack'], ],
Available channel drivers
Name Description stack
A wrapper that facilitates the creation of "multi-channel" channels single
Single file or Log channel-based path ( StreamHandler
)daily
A daily rotating Monolog-driven one RotatingFileHandler
slack
A Monolog-driven SlackWebhookHandler
syslog
A Monolog-driven SyslogHandler
##errorlog A Monolog-drivenErrorLogHandler monolog A Monolog that can use any Monolog handler Factory drivercustom A driver that calls the specified factory to create a channel{tip} For
monolog
andcustom
drivers, see Advanced Channel CustomizationConfiguring Single and Daily channels
single
anddaily
channels contain three optional configuration items:bubble
,permission
andlocking
.Name Description Default value bubble
After the message is processed, indicate whether the message is pushed to other channels true
permission
Log file permission 644
locking
Attempt to lock the log file before writing false
Configuring a Slack channel
##Building a log stackAs mentioned earlier, theslack
The channel requires theurl
configuration option. This URL should match an incoming webhook you configured for your Slack team.stack
driver allows you to log in a single Integrate multiple channels into a channel. Let's look at how to use the log stack through a production-level application configuration example: :
'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', ], ],
Let's analyze this configuration. The first thing to note is thatstack
Log levelPlease pay attention to theaggregates two other channels with the help of its
channelsoption:
syslogand
slack. Therefore, when logging a log message, both channels have the opportunity to complete the log message recording:
syslog# in the above example.
debuglevel
configuration items that exist in ## andslack
. This option determines the minimum "level" of logging that needs to be logged by this channel. Monolog (a powerful Laravel logging service) accepts all levels defined in the RFC 5424 specification:emergency
, alert, critical, error, warning, notice, info and debug. Assume we use themethod to record log messages:
syslog
According to our configuration, theLog::debug('An informational message.');
channel will record the message to the system log; But because the error message is not
critical
or higher, it will not be sent to Slack. If we log anemergency
message, it will be sent to syslog and Slack because the level ofemergency
is higher than the lowest level limit for both channels:Log::emergency('The system is down!');
Write log messageYou can use the
Logfacade to write information to the log. As mentioned before, logging provides the available logging levels defined in the RFC 5424 specification:
config/logging.phpemergency
, 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);
Therefore, you can call any of these methods The method records the corresponding level of logs. By default, messages are written to the default logging channel defined in theconfiguration 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)]); } }
Context informationYou can pass an array of context data to the log method. The information will be formatted and displayed with the log message:
Log::info('User failed to login.', ['id' => $user->id]);
Write to the specified channel
Sometimes you may want to write messages to a channel other than the application's default channel. You can use the
channel
method of theLog
facade to obtain any channel defined in the configuration file and write the message into it:Log::channel('slack')->info('Something happened!');
If you want to create a channel consisting of multiple The on-demand recording stack composed of channels can use the
stack
method:Log::stack(['single', 'slack'])->info('Something happened!');
##Highly customized Monolog channel Customizing Monolog for channelsSometimes you need to fully control the Monolog of an existing channel: For example, you may want to To configure a custom MonologFormatterInterface
First define aimplementation for log processing of a given channel:
tap
array in the channel configuration. The
taparray contains a list of classes that have the opportunity to be used to customize the Monolog instance after the channel is created:
'single' => [ 'driver' => 'single', 'tap' => [App\Logging\CustomizeFormatter::class], 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', ],
Once thetap
option is configured in the channel, To prepare a class for a custom Monolog instance. This class requires a method:
__invoke, which accepts an
Illuminate\Log\Loggerinstance as its parameter.
Illuminate\Log\LoggerThe 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(...); } } }
{tip} All "tap" classes are resolved by the service container, Therefore any constructors that depend on them will be automatically injected.
Create a Monolog processor channelMonolog has a variety of available processors. In some cases, you will want to create only a Monolog-driven log type with a specific processor. These channels can be created using themonolog
When using thedriver.
monolog
driver, the
handlerconfiguration item is used to specify the instantiated processor. If the processor's constructor requires parameters, you can use the optional
withconfiguration item to specify:
'logentries' => [ 'driver' => 'monolog', 'handler' => Monolog\Handler\SyslogUdpHandler::class, 'with' => [ 'host' => 'my.logentries.internal.datahubhost.company.com', 'port' => '10000', ], ],
Monolog formattingUsemonolog
When driven, Monolog's
LineFormatteris used as the default formatter. Of course, you can also use the
formatterand
formatter_withconfiguration items to customize the formatting processor type:
'browser' => [ 'driver' => 'monolog', 'handler' => Monolog\Handler\BrowserConsoleHandler::class, 'formatter' => Monolog\Formatter\HtmlFormatter::class, 'formatter_with' => [ 'dateFormat' => 'Y-m-d', ], ],
If the Monolog processor used can provide its own format generation processor, you can specify theformatter
configuration item as
default:
'newrelic' => [ 'driver' => 'monolog', 'handler' => Monolog\Handler\NewRelicHandler::class, 'formatter' => 'default', ],
Creating channels through factories
If you want to define a completely custom channel, you have full control over Monolog instantiation and configuration, you can configure it in
config/logging.php
Specify thecustom
driver type in the file. Your configuration should include avia
option pointing to the factory class that will be called to create the Monolog instance:'channels' => [ 'custom' => [ 'driver' => 'custom', 'via' => App\Logging\CreateCustomLogger::class, ], ],
Once the
custom
channel is configured, you can define the creation Class for Monolog instances. This class only needs one method:__invoke
, which can return a 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(...); } }