I need to track and update all the log activities by the user in a user log file with name of the log file has storage/log/{Auth::user()->}_26_02_2021.log.
How can I achieve this using Laravel Logger.
I searched google found no useful tutorials.
I need to track and update all the log activities by the user in a user log file with name of the log file has storage/log/{Auth::user()->}_26_02_2021.log.
How can I achieve this using Laravel Logger.
I searched google found no useful tutorials.
Let me only answer this question. How I found the solution to the above question.
I created a tap File like this inside a App\Logging folder
namespace App\Logging;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\FormattableHandlerInterface;
use Monolog\Formatter\LineFormatter;
class CustomLogFilenames
{
/**
* Customize the given logger instance.
*
* @param \Illuminate\Log\Logger $logger
* @return void
*/
public function __invoke($logger)
{
foreach ($logger->getHandlers() as $handler) {
if ($handler instanceof RotatingFileHandler) {
$userId = auth()->user()->id;
$handler->setFilenameFormat("{filename}-$userId-{date}", 'Y-m-d');
}
if ($handler instanceof FormattableHandlerInterface) {
$handler->setFormatter( new LineFormatter("[%datetime%]: %message% \n", 'Y-m-d H:i:s', true));
}
}
}
}
And added the following configuration inside the config\logging
'userTracker' => [
'driver' => 'daily',
'tap' => [App\Logging\CustomLogFilenames::class],
'path' => storage_path('logs/user-id.log'),
'level' => 'debug',
],
I added this in the Controller
\Log::channel('userTracker')->info('Edit the Page');
it created a file with name user-id-100-2020-02-26.log
For this case you must create simple "custom log formatter" like this:
//app\Utils\Logs\UserLogger.php
class UserLogger
{
public function __invoke(array $config): Logger
{
$log = new Logger($config['logname']);
$level = $log::toMonologLevel($config['level'] ?: 'debug');
$currUserId = auth()->user()->id;
$logPath = storage_path('logs/by_user/' . $currUserId . '/' . Carbon::now()->toDateString() . '.log');
$log->pushHandler(new StreamHandler($logPath, $level, false));
return $log;
}
}
//app\Http\Middleware\AdminMiddleware.php
class AdminMiddleware
{
public function handle(Request $request, Closure $next)
{
$uri = $request->path();
$requestParams = $request->all();
logs('by_user_logs')->info('this user want to: ', ['uri' => $uri, 'params' => $requestParams]);
//...
}
}
//config\logging.php
'channels' => [
//...
'by_user_logs' => [
'driver' => 'custom',
'via' => UserLogger::class,
'logname' => 'by_user_logs',
'level' => 'debug',
],
//...
],