Laravel Tip !
Thông thường thì các ứng dụng nào cũng cần có một tệp logs để ghi lại nhật ký hoạt động của website, Trong Laravel ta có thể tự custom một tệp logs theo ý mình, chẳng hạn cách dụng dưới đây.
// 🖍 Cài đặt package
// 👉 composer require symfony/http-foundation
// 🖍 Khai báo lớp BinaryFileResponse
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\Stream;
use Carbon\Carbon;
Route::get('/logs', function () {
$now = Carbon::now('Asia/Ho_Chi_Minh');
// 👉 lấy IP của người dùng
$ip = request()->ip();
// 📌 Lấy đường dẫn request
$fullUrl = request()->fullUrl();
// 📄 Ghi chú thông tin file Logs
$logEntry = $now->format('Y-m-d H:i:s') . ' - ' . $ip . ' - ' . $fullUrl . "\n";
// 🛠 Cài đặt đường dẫn tới tệp logs
// 🚀 Chúng ta có thể tạo tệp logs theo tên user hoặc ip,...
$filePath = storage_path('logs/request_logs.txt');
// 🔍 Kiểm tra tệp logs đã tồn tại chưa, nếu chưa thì sẽ tạo nó
if (!file_exists($filePath)) {
file_put_contents($filePath, 'This is a newly created file.'."\n");
}
// ✅ Viết thêm logs vào tệp
file_put_contents($filePath, $logEntry, FILE_APPEND);
try {
$stream = new Stream($filePath);
return new BinaryFileResponse($stream);
} catch (\Exception $e) {
return response()->json(['error' => 'An error occurred while streaming the file'], 500);
}
});
Cách trên là một cách ghi logs đơn giản, nếu bạn thích thì tạo một lớp Middleware để xử lý việc lưu logs cũng khá ngon đấy