PHPackages                             makaveli/laravel-logger - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. makaveli/laravel-logger

ActiveLibrary[Framework](/categories/framework)

makaveli/laravel-logger
=======================

Advanced Logger for Laravel

1.1.5(1mo ago)0284MITPHPPHP ^8.2

Since Apr 25Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/Ma1kaveli/laravel-logger)[ Packagist](https://packagist.org/packages/makaveli/laravel-logger)[ RSS](/packages/makaveli-laravel-logger/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (6)Versions (22)Used By (4)

makaveli/laravel-logger
=======================

[](#makavelilaravel-logger)

[![Packagist Version](https://camo.githubusercontent.com/d3cbf9ac52359b67f3c83c989f968337908a5752432b1cc1bd18455fb2c50bcd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d616b6176656c692f6c61726176656c2d6c6f676765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/makaveli/laravel-logger)[![Packagist Downloads](https://camo.githubusercontent.com/a068c8502601a80604653deb32db39e9074754b9259f420957db6b19461d359d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d616b6176656c692f6c61726176656c2d6c6f676765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/makaveli/laravel-logger)[![License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](LICENSE)

🌍 Languages
-----------

[](#-languages)

- 🇺🇸 English (default)
- 🇷🇺 [Русская версия](docs/ru/README.md)

Table of Contents
-----------------

[](#table-of-contents)

1. [Introduction](#introduction)
2. [Requirements](#requirements)
3. [Installation](#installation)
4. [Configuration](#configuration)
5. [Core Components](#core-components)
    - [Traits](#traits)
    - [LogRepository](#logrepository)
    - [DTO](#dto)
    - [Filters](#filters)
    - [Resources](#resources)
    - [Console Commands](#console-commands)
6. [Database Schema](#database-schema)
7. [Quick Start](#quick-start)
8. [Integration with BaseRepository](#integration-with-baserepository)
9. [Extending the Package](#extending-the-package)
10. [Recommendations](#recommendations)
11. [Useful Links](#useful-links)

Introduction
------------

[](#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 `BaseRepository` and `BaseQueryBuilder` for consistent data access.

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 10.10, 11.0, or 12.0
- [makaveli/laravel-core](https://github.com/Ma1kaveli/laravel-core) (v1.0.4)
- [makaveli/laravel-query-builder](https://github.com/Ma1kaveli/laravel-query-builder) (v1.1.5)

Installation
------------

[](#installation)

1. Install the package via Composer:

    ```
    composer require makaveli/laravel-logger
    ```
2. (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`.
3. Run the package migrations to create the required database tables:

    ```
    php artisan migrate:logger
    ```

    This creates the `logs` schema and tables `logs.action_logs` and `logs.logs`.

Configuration
-------------

[](#configuration)

The configuration file `config/logger.php` allows you to customize the following parameters:

ParameterDescriptionDefault`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
---------------

[](#core-components)

### Traits

[](#traits)

The package provides two traits for logging actions:

#### `Logger`

[](#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 `$data` to contain `code` and optionally `message`.

#### `AsyncLogger`

[](#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

[](#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 `$dto` parameters. The `$filterType` can be `'users'` or `'organizations'`, affecting the related user/organization data included in the result.

### DTO

[](#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:**

ParameterTypeDescription`dateFrom`stringStart date (Y-m-d)`dateTo`stringEnd date (Y-m-d)`userId`intFilter by user ID`organizationId`intFilter by organization ID`actionLogId`intFilter by action log ID`search`stringSearch 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

[](#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

[](#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

[](#console-commands)

CommandDescription`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
---------------

[](#database-schema)

The package creates the `logs` schema and two tables:

### `logs.action_logs`

[](#logsaction_logs)

ColumnTypeDescription`id`bigint (PK)Auto‑increment ID`name`stringHuman‑readable action name`slug`stringUnique identifier (e.g., `user.login`)`description`textOptional description`created_at`timestampCreation time`updated_at`timestampLast update time### `logs.logs`

[](#logslogs)

ColumnTypeDescription`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`textError message if any`description`textCustom description (generated by callback)`is_error`booleanFlag indicating failure`created_at`timestampCreation time`updated_at`timestampLast update timeQuick Start
-----------

[](#quick-start)

### 1. Configure slugs

[](#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

[](#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

[](#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
-------------------------------

[](#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
---------------------

[](#extending-the-package)

You can customize the package by overriding:

- **Models**: Extend `Logger\Models\ActionLog` or `Logger\Models\Log` and update the configuration if needed (though not directly configurable, you can bind your own models in a service provider).
- **Filters**: Override the `LogFilters` class by creating your own filter class and modifying the `LogRepository` or the DTO logic.
- **Resources**: Create your own `LogResource` or `ActionLogResource` to change the JSON output.
- **User Resource**: Specify a different class in `config/logger.php` under `user_resource`.

Recommendations
---------------

[](#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_callback`** to generate human‑readable log entries automatically.
- **Use the `softMethodLogger`** for 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
------------

[](#useful-links)

- Package repository:
- Base dependencies:
    - [makaveli/laravel-query-builder](https://github.com/Ma1kaveli/laravel-query-builder)
    - [makaveli/laravel-core](https://github.com/Ma1kaveli/laravel-core)

---

**Happy logging!** 🚀

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance91

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~17 days

Total

21

Last Release

44d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ed91cef75c6ac70dbc36843a28453115d78996faf342c9d0f86d89283b751522?d=identicon)[Ma1kaveli](/maintainers/Ma1kaveli)

---

Top Contributors

[![Ma1kaveli](https://avatars.githubusercontent.com/u/74207027?v=4)](https://github.com/Ma1kaveli "Ma1kaveli (21 commits)")

---

Tags

frameworklaravel

### Embed Badge

![Health badge](/badges/makaveli-laravel-logger/health.svg)

```
[![Health](https://phpackages.com/badges/makaveli-laravel-logger/health.svg)](https://phpackages.com/packages/makaveli-laravel-logger)
```

###  Alternatives

[codewithdennis/larament

Larament is a time-saving starter kit to quickly launch Laravel 13.x projects. It includes FilamentPHP 5.x pre-installed and configured, along with additional tools and features to streamline your development workflow.

3691.5k](/packages/codewithdennis-larament)[kompo/kompo

Laravel &amp; Vue.js FullStack Components for Rapid Application Development

11812.4k21](/packages/kompo-kompo)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
