journal
brief introduction
In order to help you learn more about what happened in the application, Laravel provides a powerful log service to record log information to files, system error logs, and even Slacks to notify the entire team.
Under the log engine, Laravel integrates Monolog The log library provides various powerful log processors, allowing you to customize your own application log processing through them.
to configure
All configurations of the application log system are stored in the configuration file config/logging.php
This file allows you to configure the log channel of the application, so be sure to check each available channel and its configuration item. Let's take a look at some of these configuration items.
By default, Larravel uses stack
Channel to record log information, stack
Channel is used to aggregate multiple log channels to a single channel. More about building stack
, please check The following documents 。
Configure Channel Name
By default, Monolog is instantiated through the Channel Name matching the current environment, for example production
or local
, to change this value, add name
Item to channel configuration:
'stack' => [ 'driver' => 'stack', 'name' => 'channel-name', 'channels' => ['single', 'slack'], ],
Valid channel drive list
name |
describe |
---|
stack |
Aggregator for creating "multi-channel" channels |
single |
Log channel based on single file/path( StreamHandler ) |
daily |
be based on RotatingFileHandler Driven by Monolog, logs are separated by days |
slack |
be based on SlackWebhookHandler Monolog driver for |
papertrail |
be based on SyslogUdpHandler Monolog driver for |
syslog |
be based on SyslogHandler Monolog driver for |
errorlog |
be based on ErrorLogHandler Monolog driver for |
monolog |
Monolog is changed to driver, and all supported Monolog processors can be used |
custom |
Change the call assignment to create the driver of the channel |
Note: View Advanced Channel Customization Document learning monolog
and custom
Drive.
Configure Single and Daily channels
single
and daily
The channel has three optional configuration items: bubble
、 permission
and locking
。
name |
describe |
Default |
---|
bubble |
Indicates whether the message bubbles to other channels after being processed |
true |
permission |
Log file permissions |
six hundred and forty-four |
locking |
Attempt to lock the log file before writing it |
false |
Configure Papertrail channel
papertrail
Channel requirements url
and port
You can configure options from Papertrail Get these values in.
Configure Slack Channel
slack
One channel is required url
Configuration item, this URL needs to be consistent with the Slack team you configured Request URL Match.
Build Log Stack
As mentioned above, stack
The driver allows you to combine multiple channels into a single log channel. To illustrate how to implement it, let's look at an example configuration you may see in the production environment:
'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. First, note stack
Passage through channels
The item will aggregate the other two channels: syslog
and slack
。 Therefore, when logging information, both channels have the opportunity to log information.
log level
Note that in the above example syslog
and slack
The level
Configuration item, which determines the minimum "level" that log information must reach for channel recording. Monolog, which provides log services for Laravel, supports the definition in RFC 5424 Specification All log levels in: emergency 、 alert 、 critical 、 error 、 warning 、 notice 、 info and debug 。
Therefore, suppose we use debug
Method to record log information:
Log::debug('An informational message.');
Given our configuration, syslog
The channel will record the information to the system log; However, because the error message is not critical
Or higher will not be sent to Slack. But if we record emergency
Level information will be sent to the system log and Slack because emergency
The level is higher than the minimum level threshold of two channels:
Log::emergency('The system is down!');
Write log information
You can use Log
Facade Log information is recorded. As described above, the log system provides RFC 5424 Specification Eight log levels in: 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);
Therefore, you can call any of these methods to record log information at the corresponding level. By default, the information will be written to the configuration file config/logging.php
Default channels configured:
<? php namespace App\Http\Controllers; use App\User; use Illuminate\Support\Facades\Log; use App\Http\Controllers\Controller; class UserController extends Controller { /** *Display the properties of the specified user * * @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 Information
The context data will also be passed to the log method in the form of an array, and then formatted and displayed together with the log information:
Log::info('User failed to login.', ['id' => $user->id]);
Write to the specified channel
Sometimes you may want to log information to a channel other than the default channel of the application. To achieve this, you can use Log
On the facade channel
Method to obtain the channel defined in the configuration file and write the log in:
Log::channel('slack')->info('Something happened!');
If you want to create an on-demand log stack composed of multiple channels, you can use stack
method:
Log::stack(['single', 'slack'])->info('Something happened!');
Advanced Monolog Channel Customization
Customizing Monolog for Channels
Sometimes you may need to fully control the configuration of Monolog in a channel. For example, you may want to configure a custom Monolog for the processor of a given channel FormatterInterface
realization.
As a start, we define a tap
Array, this tap
The array needs to contain a list of classes that can customize the created Monolog instance:
'single' => [ 'driver' => 'single', 'tap' => [App\Logging\CustomizeFormatter::class], 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', ],
Configured on the channel tap
Then you can define the class of the custom Monolog instance. This class only needs one access Illuminate\Log\Logger
Method of instance: __invoke
, Illuminate\Log\Logger
The instance will proxy all methods that call the underlying Monolog instance:
<? php namespace App\Logging; class CustomizeFormatter { /** * Customize the given logger instance. * * @param \Illuminate\Log\Logger $logger * @return void */ public function __invoke($logger) { foreach ($logger->getHandlers() as $handler) { $handler->setFormatter(...); } } }
Note: All tap classes pass the Service Container Parse, so all constructor dependencies they need will be automatically injected.
Create Monolog Processor Channel
Monolog has multiple Available processors In some cases, the type of logger you want to create is just a Monolog driver with a specified processor instance. These channels can be accessed through monolog
Drive creation.
use monolog
When driving, handler
The configuration item is used to specify which processor to instantiate. As an optional processor constructor parameter, you can use the handler_with
Configure items to set:
'logentries' => [ 'driver' => 'monolog', 'handler' => Monolog\Handler\SyslogUdpHandler::class, 'handler_with' => [ 'host' => 'my.logentries.internal.datahubhost.company.com', 'port' => '10000', ], ],
Monolog Formatter
use monolog
When driving, Monolog LineFormatter
Will be used as the default formatting tool. However, you can also use formatter
and formatter_with
The configuration item defines the type of formatting tool passed in to the processor:
'browser' => [ 'driver' => 'monolog', 'handler' => Monolog\Handler\BrowserConsoleHandler::class, 'formatter' => Monolog\Formatter\HtmlFormatter::class, 'formatter_with' => [ 'dateFormat' => 'Y-m-d', ], ],
If you use a Monolog processor that can provide formatting tools, you can formatter
The value of the configuration item is set to default
:
'newrelic' => [ 'driver' => 'monolog', 'handler' => Monolog\Handler\NewRelicHandler::class, 'formatter' => 'default', ],
Create a channel through the factory
If you want to define a complete custom channel so that you can fully control the instantiation and configuration of Monolog, you can set it in the configuration file config/logging.php
Specify one in custom
Drive type. In addition, your configuration should also include a via
Item to specify the factory class called to create the Monolog instance:
'channels' => [ 'custom' => [ 'driver' => 'custom', 'via' => App\Logging\CreateCustomLogger::class, ], ],
Good configuration custom
After the channel, you can define the class to create the Monlog instance. This class only needs a method to return the Monlog instance: __invoke
:
<? php namespace App\Logging; use Monolog\Logger; class CreateCustomLogger { /** * Create a custom Monolog instance. * * @param array $config * @return \Monolog\Logger */ public function __invoke(array $config) { return new Logger(...); } }