rap2hpoutre / laravel-log-viewer

:dromedary_camel: Laravel log viewer
MIT License
3.14k stars 374 forks source link

Intercept logs before view #292

Open AmraniCh opened 1 year ago

AmraniCh commented 1 year ago

Hey, thanks for the package! I want to know if it possible to intercept logs before they passed to the view ? I want to filter the logs based on some criteria related to my app business logic, is there any thing I can do to achieve that ?

Clinton594 commented 11 months ago

` // Initialize response class $Response = new Response; $response = $Response::get();

// Get request parameters for pagination
$page = (int) $request->input('page') ?: 1;
$limit = (int) $request->input('limit') ?: 1;

try {
  $logger  = new LaravelLogViewer;

  // Get all error logs
  $data = $logger->all();

  // Extract the only the keys that i need
  $data = array_map(fn ($error) => array_extract($error, ['level',  'level_class', 'level_img', 'date', 'text'], false), $data);

  // Filter by error type
  if ($request->level) {
    $data = array_filter($data, fn ($error) => $error['level'] === $request->level);
  }

  // Search the error
  if ($request->search) {
    $data = array_filter($data, fn ($error) => stripos($error['text'], $request->search) > -1);
  }

  // reindex the array keys after filtering
  $data = array_values($data);

  // Build pagination data on it
  $files = collect($data);
  $slice = $files->slice(($page - 1) * $limit, $limit);
  $paginator = new \Illuminate\Pagination\LengthAwarePaginator($slice, $files->count(), $limit);

  // Build response
  $response = $Response::set(['data' => $paginator], true);
  //code...
} catch (\Throwable $th) {
  $response = $Response::set(['message' => $th->getMessage(), 'code' => getExceptionCode($th)]);
}
return $response;`