lumen cli日誌和普通日誌分開儲存

朝東發表於2021-09-09

lumen cli日誌和普通日誌分開儲存

直接上程式碼

1.自定義LogServiceProvider
<?php
namespace App\Providers;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
class LogServiceProvider extends ServiceProvider
{
    public function __construct($app)
    {
        parent::__construct($app);
    }

    public function boot(Request $request){
        $addr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
        // 新增的請求標識
        $requestId =  $request['request_id'] = md5(time() . rand(1 , 1000));
        $file = storage_path("logs/log.log");
        if(app()->runningInConsole()){
            $file = storage_path("logs/cli-log.log");
        }
        //輸出指定格式
        $outInput = "[%datetime%][ip:$addr][requestId:{$requestId}][Level:%level_name%][Message:%message% %context% %extra%]\n";
        $handlers[] = (new RotatingFileHandler($file, 5))
            ->setFormatter(new LineFormatter($outInput, 'Y-m-d H:i:s' , true, true));
        $this->app['log']->setHandlers($handlers);
    }
}
2.引入LogServiceProvider
//在bootstrap\app.php中引入
$app->register(App\Providers\LogServiceProvider::class);
本作品採用《CC 協議》,轉載必須註明作者和本文連結
HAPPYDONG

相關文章