Core Concept: The Request Lifecycle
Konsep Inti: Siklus Hidup Request
To log the total processing time, we need to:- Record a start time as soon as a request enters the application. A global Middleware is the perfect tool for this.
- Record an end time and calculate the duration after the response has been sent to the user. Laravel’s
terminatingapplication event is ideal because it runs after the user has received their content, meaning our logging logic will have zero impact on perceived speed.
- Mencatat waktu mulai segera setelah sebuah request masuk ke aplikasi. Middleware global adalah alat yang paling tepat untuk ini.
- Mencatat waktu selesai dan menghitung durasi setelah respons dikirimkan ke pengguna. Event aplikasi
terminatingmilik Laravel sangat ideal karena berjalan setelah pengguna menerima konten mereka, yang berarti logika logging kita tidak akan berdampak sama sekali pada kecepatan yang dirasakan pengguna.
Step 1: Create the Middleware to Capture Start Time
Langkah 1: Buat Middleware untuk Mencatat Waktu Mulai
This middleware will run on every request, setting a unique ID and a start timestamp. Middleware ini akan berjalan pada setiap request, menetapkan ID unik dan timestamp awal. A. Create the Middleware file / Buat file Middlewareapp/Http/Middleware/CaptureRequestMetrics.php and add the following logic. This will also centralize the creation of our request_id.
Buka app/Http/Middleware/CaptureRequestMetrics.php dan tambahkan logika berikut. Ini juga akan memusatkan pembuatan request_id kita.
app/Http/Kernel.php. Add it to the $middleware property array.
Agar middleware ini berjalan pada setiap request web, tambahkan ke dalam tumpukan middleware global di app/Http/Kernel.php. Tambahkan ke array properti $middleware.
Step 2: Create the Asynchronous Job for Process Logging
Langkah 2: Buat Job Asinkron untuk Logging Proses
This Job will be responsible for writing the process timing data to its own collection in MongoDB. Job ini akan bertanggung jawab untuk menulis data waktu proses ke koleksinya sendiri di MongoDB. A. Create the Job file / Buat file Jobapp/Jobs/LogProcessTiming.php. It’s very similar to our query log job but writes to a different collection.
Buka app/Jobs/LogProcessTiming.php. Job ini sangat mirip dengan job log kueri kita tetapi menulis ke koleksi yang berbeda.
Step 3: Update the Service Provider to Log on Termination
Langkah 3: Perbarui Service Provider untuk Melakukan Log saat Terminasi
We will now modify our existingQueryLoggingServiceProvider to listen for the application’s terminating event.
Sekarang kita akan memodifikasi QueryLoggingServiceProvider yang sudah ada untuk mendengarkan event terminating dari aplikasi.
A. Modify QueryLoggingServiceProvider.php / Modifikasi QueryLoggingServiceProvider.php
Add the new listener logic to the boot() method.
Tambahkan logika listener baru ke dalam method boot().
How It Works Together
Bagaimana Semua Bekerja Bersama
- A request hits your application. Sebuah request masuk ke aplikasi Anda.
- The
CaptureRequestMetricsmiddleware runs first. It sets a uniquerequest_idand arequest_start_timeon the request object. MiddlewareCaptureRequestMetricsberjalan pertama kali. Ia menetapkanrequest_idunik danrequest_start_timepada objek request. - As your application processes the request, any database queries are caught by
DB::listen. It dispatches aLogQueryToMongojob for each query, using the samerequest_id. Saat aplikasi memproses request, setiap kueri database ditangkap olehDB::listen. Ia mengirimkan jobLogQueryToMongountuk setiap kueri, menggunakanrequest_idyang sama. - The application generates a response and sends it to the user. Aplikasi menghasilkan respons dan mengirimkannya ke pengguna.
- After the response is sent, the
terminatingevent fires. Setelah respons dikirim, eventterminatingdijalankan. - Our new listener calculates the total duration and peak memory usage. It then dispatches the
LogProcessTimingjob, also using the samerequest_id. Listener baru kita menghitung total durasi dan penggunaan memori puncak. Kemudian ia mengirimkan jobLogProcessTiming, juga menggunakanrequest_idyang sama. - Your background queue worker processes both types of jobs, saving them to
query_logsandprocess_logsrespectively. Worker antrian di latar belakang memproses kedua jenis job tersebut, menyimpannya ke koleksiquery_logsdanprocess_logssecara berurutan.
application_logs database, you can find a slow request in the process_logs collection and then use its request_id to find every single database query that was executed during that specific request in the query_logs collection.
Sekarang, di database application_logs Anda, Anda dapat menemukan request yang lambat di koleksi process_logs dan kemudian menggunakan request_id-nya untuk menemukan setiap kueri database yang dieksekusi selama request spesifik tersebut di koleksi query_logs.