S
S
Svjatoslav Torn2020-08-28 14:17:30
Journaling
Svjatoslav Torn, 2020-08-28 14:17:30

How to do dynamic logging in Laravel?

Good afternoon, there is a need to make dynamic logging in a hobby project.
Imagine a situation where we have many users and we want to log the actions of each of them in separate logs. Of course, I found a way out of the situation, but I think it can be done in one way or another.
How I implemented it:
Declared a custom channel
config/logging.php

'custom' => [
      'driver' => 'custom',
      'via' => App\Logging\CreateCustomLogger::class,
],


2. Created a handler as in the
app/logging/CreateCustomLogging.php documentation
public function __invoke(array $config)
{
    return new Logger('name');
}


3. Added a method to the interface and made its implementation
app/repositories/OfficeLogger.php
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
public function log(string $path, string $message, array $context)
{
     \Log::channel('custom')->pushHandler(new StreamHandler(storage_path($path), Logger::DEBUG))->info($message, $context);
}


And then I call where I need, like this:
app('App\Repositories\Interfaces\OfficeLoggerInterface')->log('app/office-logger/1/47/.'.date('Y').'/'.date('d-m-Y').'.log', 'Hello world message', $context);


Perhaps there is a better way to do it?
Is it okay to use app('interface') all the time?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2020-08-28
@FanatPHP

Anything to write with your hands is spaghetti.
The essence of Laravel is that everything is done automatically
. In this case, middleware is done,

<?php

namespace App\Http\Middleware;

use Closure;
use \Illuminate\Http\Request;

class UserActivityLoggerMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // тут пишешь свое логирование
       $user_id = $request->user()->id;
       $action = $request->route()->getName();
        // обяязательная строчка
        return $next($request);
    }
}

register in Kernel.php
'logger' => \App\Http\Middleware\UserActivityLoggerMiddleware::class,

and enclosing user events in a call to this middleware
Route::group(['middleware' => ['logger']], function()
{
}

A
Alex Wells, 2020-08-29
@Alex_Wells

Is this a real challenge? I.e. Do I need to output these actions somewhere, or is it for debugging? Because if the latter, then forget about logging through the code. There are nginx logs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question