makaveli / laravel-logger
Advanced Logger for Laravel
Requires
- php: ^8.2
- laravel/framework: ^10.10|^11.0|^12.0
- makaveli/laravel-core: 1.0.3
- makaveli/laravel-query-builder: 1.1.4
README
🌍 Languages
- 🇺🇸 English (default)
- 🇷🇺 Русская версия
Table of Contents
- Introduction
- Requirements
- Installation
- Configuration
- Core Components
- Database Schema
- Quick Start
- Integration with BaseRepository
- Extending the Package
- Recommendations
- Useful Links
Introduction
makaveli/laravel-logger is a comprehensive logging package for Laravel that records user actions (both successful and failed) with support for asynchronous queue processing. It provides a flexible way to store logs with action slugs, powerful filtering capabilities, and seamless integration with makaveli/laravel-core and makaveli/laravel-query-builder.
Key features:
- Logging of successful and failed actions using predefined slugs.
- Asynchronous logging via Laravel queues.
- Rich filtering by date, user, organization, action type, and search.
- Console commands to seed action logs and generate test logs.
- Configurable prefixes for success and error slugs.
- Full integration with
BaseRepositoryandBaseQueryBuilderfor consistent data access.
Requirements
- PHP 8.2 or higher
- Laravel 10.10, 11.0, or 12.0
- makaveli/laravel-query-builder (v1.1.4)
- makaveli/laravel-core (v1.0.3)
Installation
-
Install the package via Composer:
composer require makaveli/laravel-logger
-
(Optional) Publish the configuration file to customize settings:
php artisan vendor:publish --tag=logger-config
This will copy the configuration file to
config/logger.php. -
Run the package migrations to create the required database tables:
php artisan migrate:logger
This creates the
logsschema and tableslogs.action_logsandlogs.logs.
Configuration
The configuration file config/logger.php allows you to customize the following parameters:
| Parameter | Description | Default |
|---|---|---|
success_prefix |
Prefix for success action slugs | 'success' |
error_prefix |
Prefix for error action slugs | 'error' |
user_model |
User model class | App\Models\User::class |
user_resource |
Resource class for formatting user data | [\App\Modules\Base\Resources\UserShortResource::class, 'once'] |
slug_list |
Array of slugs to seed via seed:action-logs |
[] |
logs_factory_count |
Number of test logs to generate via seed:test-logs |
1000 |
repository.description_callback |
Callback to generate custom log descriptions | null |
Example configuration:
return [ 'success_prefix' => 'success', 'error_prefix' => 'error', 'user_model' => App\Models\User::class, 'user_resource' => [\App\Modules\Base\Resources\UserShortResource::class, 'once'], 'slug_list' => [ ['name' => 'User Login', 'slug' => 'user.login'], ['name' => 'User Logout', 'slug' => 'user.logout'], ], 'repository' => [ 'description_callback' => function (\Illuminate\Contracts\Auth\Authenticatable $user, \Logger\Models\ActionLog $log) { return strtoupper($user->name) . ' did: ' . $log->name; } ], 'logs_factory_count' => env('LOG_FACTORY', 1000), ];
Core Components
Traits
The package provides two traits for logging actions:
Logger
Used for synchronous logging (immediate database insert).
successLog(string $slug, ?string $description = null): Logs a successful action.errorLog(string $slug, ?string $error = null): Logs a failed action with an optional error description.softMethodLogger(string $slug, array $data): Used for soft delete/restore methods; expects$datato containcodeand optionallymessage.
AsyncLogger
Same methods as Logger, but dispatches a job to the queue for asynchronous processing:
successAsyncLog(string $slug, ?string $description = null)errorAsyncLog(string $slug, ?string $error = null)softMethodAsyncLogger(string $slug, array $data)
These methods are ideal for high‑traffic applications where you don't want to wait for the database write.
LogRepository
The LogRepository class extends BaseRepository from makaveli/laravel-core and provides methods to retrieve logs with filtering.
use Logger\Repositories\LogRepository; $logRepository = new LogRepository(); $logs = $logRepository->getCustomPaginatedList($dto, 'users');
getCustomPaginatedList(ActionLogShowDTO $dto, string $filterType): Returns a paginated list of logs filtered by$dtoparameters. The$filterTypecan be'users'or'organizations', affecting the related user/organization data included in the result.
DTO
ActionLogShowDTO is a dedicated DTO that encapsulates filter parameters. It is built from the request and optionally validates user/organization access via callbacks.
use Logger\DTO\ActionLogShowDTO; $dto = ActionLogShowDTO::fromRequest($request, $actionLogId);
Available filter parameters:
| Parameter | Type | Description |
|---|---|---|
dateFrom |
string | Start date (Y-m-d) |
dateTo |
string | End date (Y-m-d) |
userId |
int | Filter by user ID |
organizationId |
int | Filter by organization ID |
actionLogId |
int | Filter by action log ID |
search |
string | Search in user fields (name, phone, email, etc.) |
You can also pass validation callbacks for userId and organizationId to enforce permissions:
$dto = ActionLogShowDTO::fromRequest( $request, $actionLogId, fn($user, $id) => $user->id === $id // user validation );
Filters
The package uses makaveli/laravel-query-builder internally. The filter class LogFilters (located in Logger\Filters) extends BaseQueryBuilder and applies the necessary filters based on the DTO. You can extend or override it if needed.
Resources
Two resources are provided to format API responses:
LogResource: Formats a single log entry.ActionLogResource: Formats an action log.
By default, ActionLogResource uses the configured user_resource to format the user data.
Console Commands
| Command | Description |
|---|---|
php artisan seed:action-logs |
Seeds action logs from the slug_list configuration. |
php artisan seed:test-logs |
Generates test logs (count defined by logs_factory_count). |
php artisan migrate:logger |
Runs the package migrations. |
Database Schema
The package creates the logs schema and two tables:
logs.action_logs
| Column | Type | Description |
|---|---|---|
id |
bigint (PK) | Auto‑increment ID |
name |
string | Human‑readable action name |
slug |
string | Unique identifier (e.g., user.login) |
description |
text | Optional description |
created_at |
timestamp | Creation time |
updated_at |
timestamp | Last update time |
logs.logs
| Column | Type | Description |
|---|---|---|
id |
bigint (PK) | Auto‑increment ID |
created_by |
bigint (FK) | User ID who performed the action |
action_log_id |
bigint (FK) | Foreign key to action_logs |
error_description |
text | Error message if any |
description |
text | Custom description (generated by callback) |
is_error |
boolean | Flag indicating failure |
created_at |
timestamp | Creation time |
updated_at |
timestamp | Last update time |
Quick Start
1. Configure slugs
Add your action slugs to the slug_list in config/logger.php:
'slug_list' => [ ['name' => 'User Login', 'slug' => 'user.login'], ['name' => 'User Logout', 'slug' => 'user.logout'], ],
Then seed them:
php artisan seed:action-logs
2. Use the logger trait in a controller
use Logger\Traits\Logger; class AuthController extends Controller { use Logger; public function login(Request $request) { if (auth()->attempt($credentials)) { $this->successLog('user.login'); return response()->json(['message' => 'Logged in']); } else { $this->errorLog('user.login', 'Invalid credentials'); return response()->json(['message' => 'Unauthorized'], 401); } } }
For asynchronous logging:
use Logger\Traits\AsyncLogger; class AuthController extends Controller { use AsyncLogger; public function login(Request $request) { // ... same as above, but use successAsyncLog / errorAsyncLog $this->successAsyncLog('user.login'); } }
3. Retrieve logs in a repository or controller
use Logger\Repositories\LogRepository; use Logger\DTO\ActionLogShowDTO; public function index(Request $request) { $dto = ActionLogShowDTO::fromRequest($request); $logs = (new LogRepository())->getCustomPaginatedList($dto, 'users'); return LogResource::collection($logs); }
Integration with BaseRepository
The LogRepository is already a descendant of BaseRepository from makaveli/laravel-core. You can use it directly in your controllers:
use Logger\Repositories\LogRepository; use Core\DTO\ListDTO; class LogController extends Controller { public function __construct(private LogRepository $logRepository) {} public function index(Request $request) { $dto = ActionLogShowDTO::fromRequest($request); $logs = $this->logRepository->getCustomPaginatedList($dto, 'users'); return response()->json($logs); } }
The repository automatically uses the LogFilters class (which extends BaseQueryBuilder) to apply all filters from the DTO.
Extending the Package
You can customize the package by overriding:
- Models: Extend
Logger\Models\ActionLogorLogger\Models\Logand update the configuration if needed (though not directly configurable, you can bind your own models in a service provider). - Filters: Override the
LogFiltersclass by creating your own filter class and modifying theLogRepositoryor the DTO logic. - Resources: Create your own
LogResourceorActionLogResourceto change the JSON output. - User Resource: Specify a different class in
config/logger.phpunderuser_resource.
Recommendations
- Always define slugs in the configuration and seed them before using them.
- Use asynchronous logging for high‑volume actions to keep response times low.
- Leverage the DTO’s validation callbacks to restrict log access based on user permissions (e.g., only allow admins to see all logs, while regular users see only their own).
- Set a sensible
description_callbackto generate human‑readable log entries automatically. - Use the
softMethodLoggerfor soft delete/restore actions to capture both success and failure states with a single call. - Index database columns (
created_by,action_log_id,created_at) for better performance on filtered queries.
Useful Links
- Package repository: https://github.com/Ma1kaveli/laravel-logger
- Base dependencies:
Happy logging! 🚀