0

I have two logger classes.

1. RequestLogger (logs all incoming api request to the DB)
2. SqlLogger (logs all sql queries to the log file)

I currently have them defined as classes in helper files:

1. app/Helpers/RequestLogger.php
2. app/Helpers/SqlLogger.php

However, I am not sure if that is the right way to do it. Would they rather be ServiceProviders than helpers? At the moment it is hard for me to define what is a helper and what a serviceprovider in this context.

Rob
  • 2,243
  • 4
  • 29
  • 40
Chris
  • 13,100
  • 23
  • 79
  • 162

1 Answers1

0

Generally speaking, the files/classes all are same php code and it depends on your preference how you organize those. In this case, depending on the operation each class does, you may store them in different places and name them using different conventions. For example, in your case, the request logger is a good candidate to be a middleware. Since each api request needs to be logged so create a middleware, for example:

namespace App\Http\Middleware;

use Closure;
use App\Models\Log;

class ApiRequestLogger
{

    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Create the log entry here...

        return $response;
    }
}

To use this middleware, you need to register it in app\Http\Kernel.php class. Simply, you may add this in api group or you can add it in $routeMiddleware using something like this:

'log' => \App\Http\Middleware\ApiRequestLogger::class,

Now, you may use it in each api route by adding the middleware in route declarations individually or group wise, depending on how you registered it.

The query log is a bit different (logically), since you want to log each sql query then you can simply register the following event in AppServiceProvider or your own service provider in the the boot method:

\DB::listen(function ($query) {
    // Your code here ...
    // $query->sql
    // $query->bindings
    // $query->time
    // \Log::debug($query->sql . ' - ' . serialize($query->bindings));
});

Now, this seems okay to me but instead of putting all the log related code, you may use a separate class/helper file to store the logging related code so it's up to you. If your query log is simple enough then why bother another separate class/file but you may use a separate class for it and store the class in a completely new directory, i.e: services\QueryLogger.php or whatever it feels right to you but there is no best or predefined way, Laravel doesn't forces you to organize your code. Just keep it simple.


Note: These are my opinions only. An answer about query logging here.

The Alpha
  • 143,660
  • 29
  • 287
  • 307