Answer the question
In order to leave comments, you need to log in
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,
],
public function __invoke(array $config)
{
return new Logger('name');
}
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);
}
app('App\Repositories\Interfaces\OfficeLoggerInterface')->log('app/office-logger/1/47/.'.date('Y').'/'.date('d-m-Y').'.log', 'Hello world message', $context);
Answer the question
In order to leave comments, you need to log in
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);
}
}
'logger' => \App\Http\Middleware\UserActivityLoggerMiddleware::class,
Route::group(['middleware' => ['logger']], function()
{
}
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 questionAsk a Question
731 491 924 answers to any question