# Laravel Logging
https://laravel.com/docs/8.x/logging#introduction
> 日誌紀錄是基於 channel,利用 monolog library
# 設定
- 設定檔 `config/logging.php`
- 預設是使用 stack channel,將多個 log channel 變成單一個
## 設定 channel name
```php=
'stack' => [
'driver' => 'stack',
'name' => 'channel-name',
'channels' => ['single', 'slack'],
],
```
可以用的 [drivers](https://laravel.com/docs/8.x/logging#available-channel-drivers)
## Channel Prerequisites
需要一些前置作業
- [single 和 daily](https://laravel.com/docs/8.x/logging#configuring-the-single-and-daily-channels)
- [Papertrail](https://laravel.com/docs/8.x/logging#configuring-the-papertrail-channel)
- [slack](https://laravel.com/docs/8.x/logging#configuring-the-slack-channel)
## Logging Deprecation Warnings
有時候需要通知某些功能在未來會背棄用
```php=
'deprecations' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
```
# 建立 Log Stacks
```php=
'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 那一部分有兩個 channel,syslog 和 slack 當logging的時候這兩個都有機會去log message
## Log Levels
[RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424) specification 定義的 log level
- emergency
- alert
- critical
- error
- warning
- notice
- info
- debug
所以當我們 log 一個 debug 的訊息 `syslog` channel 會寫入一筆訊息到系統LOG但是部會寫入到 `slack` 因為不是 critical 等級的 LOG
```php=
// debug log level
Log::debug('An informational message.');
// emergency log level
Log::emergency('The system is down!');
```
# Writing Log Messages
```php=
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);
```
## Contextual Information
帶參數
```php=
use Illuminate\Support\Facades\Log;
Log::info('User failed to login.', ['id' => $user->id]);
```
需要接下來的 log 都有 request id
```php=
Log::withContext([
'request-id' => $requestId
]);
```
## Writing To Specific Channels
```php=
// 單一
Log::channel('slack')->info('Something happened!');
// 多個
Log::stack(['single', 'slack'])->info('Something happened!');
```
## On-Demand Channels
不需要先 logging configuration file
```php=
use Illuminate\Support\Facades\Log;
Log::build([
'driver' => 'single',
'path' => storage_path('logs/custom.log'),
])->info('Something happened!');
```
You may also wish to include an on-demand channel in an on-demand logging stack.
```php=
use Illuminate\Support\Facades\Log;
$channel = Log::build([
'driver' => 'single',
'path' => storage_path('logs/custom.log'),
]);
Log::stack(['slack', $channel])->info('Something happened!');
```
###### tags: `2021` `laravel` `log` `monolog`
{%hackmd BJrTq20hE %}