[英]Laravel Log Customer Log file with UserId and date
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.我需要在用户日志文件中跟踪和更新用户的所有日志活动,该日志文件的名称为 storage/log/{Auth::user()->}_26_02_2021.log。
How can I achieve this using Laravel Logger.如何使用 Laravel 记录器来实现这一点。
I searched google found no useful tutorials.我搜索谷歌发现没有有用的教程。
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',
],
//...
],
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我在 App\Logging 文件夹中创建了一个这样的点击文件
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并在 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我在 Controller 中添加了这个
\Log::channel('userTracker')->info('Edit the Page');
it created a file with name user-id-100-2020-02-26.log它创建了一个名为 user-id-100-2020-02-26.log 的文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.