原本的log預設儲存於storage/log/laravel.log
,如果想改個檔案名稱或是儲存路徑時呢?
Laravel 並沒有提供相關的設定,而是把這部分寫死在
Illuminate\Foundation\Bootstrap\ConfigureLogging
裡頭
/**
* Configure the Monolog handlers for the application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @param \Illuminate\Log\Writer $log
* @return void
*/
protected function configureSingleHandler(Application $app, Writer $log)
{
$log->useFiles($app->storagePath().'/logs/laravel.log');
}
天無絕人之路,所幸我們可以自己建立個 Class
繼承 ConfigureLogging
來覆寫原始的設定:
首先我們在 bootstrap
資料夾底下自己建立個 ConfigureLogging.php
<?php
namespace App\Bootstrap;
use Illuminate\Log\Writer;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Foundation\Bootstrap\ConfigureLogging as IlluminateConfigureLogging;
class ConfigureLogging extends IlluminateConfigureLogging {
protected function configureSingleHandler(Application $app, Writer $log) {
// 這裡可以自己設置路徑或是檔案名稱
$log->useFiles($app->storagePath().'/logs/xxx.log');
}
}
要注意的是這邊只覆寫了 configureSingleHandler
,也就是當你的 config/app.php
或 .env
中的 log設定為 single
時,其他模式以此類推。
/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/
'log' => env('APP_LOG', 'single'),
但是這樣還沒完,我們必須替換掉預設的 Illuminate\Foundation\Bootstrap\ConfigureLogging
,有兩個地方 App\Console\Kernel
、 App\Http\Kernel
,這兩個地方一樣是覆寫繼承類的設定,除了 $bootstrappers
內容稍有不同,其他操作都一樣,所以我只舉例替換 App\Http\Kernel
部分
App\Http\Kernel
繼承了 Illuminate\Foundation\Http\Kernel
,可以看到父類中
protected $bootstrappers = [
'Illuminate\Foundation\Bootstrap\DetectEnvironment',
'Illuminate\Foundation\Bootstrap\LoadConfiguration',
'Illuminate\Foundation\Bootstrap\ConfigureLogging', <-- 要更改的
'Illuminate\Foundation\Bootstrap\HandleExceptions',
'Illuminate\Foundation\Bootstrap\RegisterFacades',
'Illuminate\Foundation\Bootstrap\SetRequestForConsole',
'Illuminate\Foundation\Bootstrap\RegisterProviders',
'Illuminate\Foundation\Bootstrap\BootProviders',
];
把這段複製到 App\Http\Kernel
,並把其中的 Illuminate\Foundation\Bootstrap\ConfigureLogging
改成 App\Bootstrap\ConfigureLogging
即可。
protected $bootstrappers = [
'Illuminate\Foundation\Bootstrap\DetectEnvironment',
'Illuminate\Foundation\Bootstrap\LoadConfiguration',
'App\Bootstrap\ConfigureLogging',
'Illuminate\Foundation\Bootstrap\HandleExceptions',
'Illuminate\Foundation\Bootstrap\RegisterFacades',
'Illuminate\Foundation\Bootstrap\SetRequestForConsole',
'Illuminate\Foundation\Bootstrap\RegisterProviders',
'Illuminate\Foundation\Bootstrap\BootProviders',
];
Ref:https://laracasts.com/discuss/channels/laravel/laravel-51-change-log-filename?page=1
网友评论