v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\ActivityLog;
use Monolog\Logger;
/**
* Monolog 커스텀 채널 팩토리.
*
* config/logging.php의 'activity' 채널에서 via 클래스로 사용됩니다.
* Laravel의 custom 드라이버가 __invoke($config)를 호출하여 Monolog Logger를 반환합니다.
*/
class ActivityLogChannel
{
/**
* 활동 로그 전용 Monolog Logger 인스턴스를 생성합니다.
*
* @param array $config 채널 설정
* @return Logger
*/
public function __invoke(array $config): Logger
{
$logger = new Logger('activity');
$logger->pushProcessor(new ActivityLogProcessor);
$logger->pushHandler(new ActivityLogHandler);
return $logger;
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\ActivityLog;
use App\Enums\ActivityLogType;
use App\Models\ActivityLog;
use Illuminate\Database\Eloquent\Model;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Level;
use Monolog\LogRecord;
/**
* 활동 로그 전용 Monolog Handler.
*
* Monolog context에서 구조화 데이터를 추출하여 activity_logs 테이블에 저장합니다.
* ActivityLogChannel에서 등록되어 Log::channel('activity') 호출 시 동작합니다.
*/
class ActivityLogHandler extends AbstractProcessingHandler
{
/**
* @param Level $level 최소 로그 레벨
* @param bool $bubble 버블링 여부
*/
public function __construct(Level $level = Level::Debug, bool $bubble = true)
{
parent::__construct($level, $bubble);
}
/**
* 로그 레코드를 activity_logs 테이블에 저장합니다.
*
* @param LogRecord $record Monolog 로그 레코드
* @return void
*/
protected function write(LogRecord $record): void
{
if (! config('activity_log.enabled', true)) {
return;
}
$context = $record->context;
$data = [
'log_type' => $context['log_type'] ?? ActivityLogType::System,
'action' => $record->message,
'description_key' => $context['description_key'] ?? null,
'description_params' => $context['description_params'] ?? null,
'properties' => $context['properties'] ?? null,
'changes' => $context['changes'] ?? null,
'user_id' => $context['user_id'] ?? null,
'ip_address' => $context['ip_address'] ?? null,
'user_agent' => $this->truncateUserAgent($context['user_agent'] ?? null),
];
$loggable = $context['loggable'] ?? null;
if ($loggable instanceof Model) {
$data['loggable_type'] = $loggable->getMorphClass();
$data['loggable_id'] = $loggable->getKey();
} elseif (isset($context['loggable_type'], $context['loggable_id'])) {
$data['loggable_type'] = $context['loggable_type'];
$data['loggable_id'] = $context['loggable_id'];
}
ActivityLog::create($data);
}
/**
* User-Agent 문자열을 최대 500자로 자릅니다.
*
* @param string|null $userAgent User-Agent 문자열
* @return string|null 잘린 User-Agent
*/
private function truncateUserAgent(?string $userAgent): ?string
{
if ($userAgent === null) {
return null;
}
return mb_substr($userAgent, 0, 500);
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\ActivityLog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;
/**
* 활동 로그 전용 Monolog Processor.
*
* 요청별 공통 데이터(user_id, ip_address, user_agent)를 자동 주입합니다.
* 리스너에서 명시적으로 전달하지 않은 경우에만 주입됩니다.
*/
class ActivityLogProcessor implements ProcessorInterface
{
/**
* 로그 레코드에 요청 컨텍스트 정보를 자동 주입합니다.
*
* @param LogRecord $record Monolog 로그 레코드
* @return LogRecord 컨텍스트가 주입된 로그 레코드
*/
public function __invoke(LogRecord $record): LogRecord
{
$context = $record->context;
// 리스너에서 명시적으로 전달하지 않은 경우에만 자동 주입
$context['user_id'] ??= Auth::id();
$context['ip_address'] ??= Request::ip();
$context['user_agent'] ??= Request::userAgent();
return $record->with(context: $context);
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace App\ActivityLog;
use Illuminate\Database\Eloquent\Model;
/**
* 모델 변경 감지 유틸리티.
*
* 모델의 $activityLogFields 메타데이터와 스냅샷을 비교하여
* 구조화된 변경 이력(changes JSON)을 생성합니다.
*/
class ChangeDetector
{
/**
* 모델의 현재 상태와 스냅샷을 비교하여 변경 사항을 감지합니다.
*
* @param Model $model 현재 모델 상태
* @param array|null $snapshot 변경 전 스냅샷 (toArray() 결과)
* @return array|null 변경 사항 배열 또는 변경 없으면 null
*/
public static function detect(Model $model, ?array $snapshot): ?array
{
if ($snapshot === null) {
return null;
}
$fields = static::getActivityLogFields($model);
if (empty($fields)) {
return null;
}
$changes = [];
foreach ($fields as $field => $meta) {
$old = $snapshot[$field] ?? null;
$new = $model->getAttribute($field);
// Enum 객체를 값으로 변환
if ($old instanceof \BackedEnum) {
$old = $old->value;
}
if ($new instanceof \BackedEnum) {
$new = $new->value;
}
if ($old !== $new) {
$change = [
'field' => $field,
'label_key' => $meta['label_key'],
'old' => $old,
'new' => $new,
'type' => $meta['type'] ?? 'text',
];
// enum 타입이면 라벨 키 추가
if (($meta['type'] ?? 'text') === 'enum' && isset($meta['enum'])) {
$enumClass = $meta['enum'];
$change['old_label_key'] = $old !== null ? $enumClass::tryFrom($old)?->labelKey() : null;
$change['new_label_key'] = $new !== null ? $enumClass::tryFrom($new)?->labelKey() : null;
}
$changes[] = $change;
}
}
return ! empty($changes) ? $changes : null;
}
/**
* 모델의 $activityLogFields 메타데이터를 반환합니다.
*
* @param Model $model 대상 모델
* @return array 필드 메타데이터 배열
*/
private static function getActivityLogFields(Model $model): array
{
if (property_exists($model, 'activityLogFields')) {
return $model::$activityLogFields;
}
return [];
}
}
@@ -0,0 +1,59 @@
<?php
namespace App\ActivityLog\Traits;
use App\Enums\ActivityLogType;
use Illuminate\Support\Facades\Log;
/**
* 활동 로그 기록 및 로그 타입 자동 결정 트레이트
*
* Service 훅이 관리자/사용자/시스템 등 다양한 컨텍스트에서 호출될 수 있으므로
* 요청 경로를 기반으로 log_type을 동적으로 결정합니다.
*
* - /api/admin/* 경로 → ActivityLogType::Admin
* - 그 외 HTTP 요청 → ActivityLogType::User
* - CLI/스케줄러(request 없음) → ActivityLogType::System
*/
trait ResolvesActivityLogType
{
/**
* 요청 경로를 기반으로 로그 타입을 결정합니다.
*
* @return ActivityLogType 결정된 로그 타입
*/
protected function resolveLogType(): ActivityLogType
{
$request = request();
if ($request && $request->path() !== '/') {
return $request->is('api/admin/*')
? ActivityLogType::Admin
: ActivityLogType::User;
}
return ActivityLogType::System;
}
/**
* 활동 로그를 기록합니다.
*
* context에 log_type이 명시되지 않으면 resolveLogType()으로 자동 결정합니다.
*
* @param string $action 액션명 (예: 'user.create')
* @param array $context Monolog context 배열
*/
protected function logActivity(string $action, array $context): void
{
$context['log_type'] ??= $this->resolveLogType();
try {
Log::channel('activity')->info($action, $context);
} catch (\Exception $e) {
Log::error('Failed to record activity log', [
'action' => $action,
'error' => $e->getMessage(),
]);
}
}
}