PHPackages                             juliofarra/yii2-logevent - 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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. juliofarra/yii2-logevent

ActiveYii2-extension[Logging &amp; Monitoring](/categories/logging)

juliofarra/yii2-logevent
========================

Yii2 behavior that automatically audits ActiveRecord changes (INSERT, UPDATE, DELETE) into a log table, storing JSON snapshots and diffs, with support for excluded and masked attributes.

v1.0.0(2d ago)00[1 issues](https://github.com/juliofarra/yii2-logevent/issues)MITPHPPHP &gt;=8.0

Since Jun 12Pushed yesterdayCompare

[ Source](https://github.com/juliofarra/yii2-logevent)[ Packagist](https://packagist.org/packages/juliofarra/yii2-logevent)[ RSS](/packages/juliofarra-yii2-logevent/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (2)Versions (2)Used By (0)

yii2-logevent
=============

[](#yii2-logevent)

[![Tests](https://github.com/juliofarra/yii2-logevent/actions/workflows/tests.yml/badge.svg)](https://github.com/juliofarra/yii2-logevent/actions/workflows/tests.yml)[![Latest Stable Version](https://camo.githubusercontent.com/a7cbab276de107184d195dc93d53e23907175507654c28a68a6325e484844c20/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a756c696f66617272612f796969322d6c6f676576656e742e737667)](https://packagist.org/packages/juliofarra/yii2-logevent)[![License: MIT](https://camo.githubusercontent.com/08cef40a9105b6526ca22088bc514fbfdbc9aac1ddbf8d4e6c750e3a88a44dca/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c75652e737667)](LICENSE)

Automatic audit trail for Yii2 ActiveRecord models.

Attach a single behavior to any ActiveRecord model and every change is logged to a database table:

EventWhat gets logged`INSERT`Full record snapshot, as JSON`UPDATE`Only the diff — old and new values of changed attributes, as JSON`DELETE`Full record snapshot, as JSONEach log entry also records **who** (user ID), **when** (timestamp) and **from where** (client IP).

> Documentación en español: [README.es.md](README.es.md)

Features
--------

[](#features)

- One-line setup: declare the behavior and the model is audited.
- **Excluded attributes**: invisible to the log — never stored, and changes to them alone don't create a log entry.
- **Masked attributes**: the log records that the attribute was set or changed, but its value is always replaced with `*****` (ideal for passwords, tokens and other secrets).
- **Configurable log table**: different models can log to different tables.
- Logging failures never break the operation being logged.
- Works in web and console applications.
- Database agnostic: PostgreSQL, MySQL/MariaDB and SQLite covered by tests.

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

[](#requirements)

- PHP &gt;= 8.0
- Yii2 &gt;= 2.0.45
- For native JSON columns: PostgreSQL 9.4+, MySQL 5.7+ or MariaDB 10.2+. On other databases (e.g. SQLite) the JSON payload is stored in a text column transparently.

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

[](#installation)

```
composer require juliofarra/yii2-logevent
```

Migration
---------

[](#migration)

The package ships a namespaced migration that creates the `log_event` table. Add the namespace to your console configuration:

```
// console/config/main.php (or config/console.php)
'controllerMap' => [
    'migrate' => [
        'class' => 'yii\console\controllers\MigrateController',
        'migrationNamespaces' => [
            'console\migrations',           // your own migrations
            'lab37\logevent\migrations',    // yii2-logevent
        ],
    ],
],
```

Then run:

```
php yii migrate
```

The table created is:

ColumnTypeDescription`id`int, PK`entity`stringTable name of the audited record (polymorphic reference, together with `entity_id`)`entity_id`bigintID of the audited record`event`string`INSERT`, `UPDATE` or `DELETE``data`jsonSnapshot or diff`user_id`int, nullUser who performed the action`created_at`timestampWhen it happened (DB default `CURRENT_TIMESTAMP`)`ip`string(45), nullClient IP (IPv4/IPv6)Usage
-----

[](#usage)

Declare the behavior in any ActiveRecord model:

```
use lab37\logevent\LogEventBehavior;

class Order extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            'logEvent' => [
                'class' => LogEventBehavior::class,
            ],
        ];
    }
}
```

That's it. Every insert, update and delete on `Order` is now logged.

### Excluding and masking attributes

[](#excluding-and-masking-attributes)

```
'logEvent' => [
    'class'   => LogEventBehavior::class,
    'exclude' => ['internal_token'],   // invisible to the log
    'mask'    => ['password'],         // logged, but value hidden
],
```

- **`exclude`** — the attribute never appears in the logged JSON. If an update only changes excluded attributes, no log entry is created at all.
- **`mask`** — the attribute appears in the logged JSON, so you know it was set or changed, but its value is always `*****` (configurable via `maskValue`). A `null` masked value is kept as `null`, so the log still shows whether the field was loaded.

Example of a logged `UPDATE` with a masked `password`:

```
{
    "status":   {"old": "draft", "new": "sent"},
    "password": {"old": "*****", "new": "*****"}
}
```

### Behavior reference

[](#behavior-reference)

PropertyDefaultDescription`idAttribute``'id'`Attribute that identifies the owner record`logEventClass``LogEvent::class`ActiveRecord class used to store log entries`exclude``[]`Attributes invisible to the log`mask``[]`Attributes logged with their value hidden`maskValue``'*****'`Replacement value for masked attributes### Logging different models to different tables

[](#logging-different-models-to-different-tables)

Create a subclass of `LogEvent` that points to another table (create that table with the same structure first):

```
use lab37\logevent\models\LogEvent;

class OrderLogEvent extends LogEvent
{
    public static function tableName()
    {
        return '{{%order_log_event}}';
    }
}
```

And configure it in the behavior:

```
'logEvent' => [
    'class'         => LogEventBehavior::class,
    'logEventClass' => OrderLogEvent::class,
],
```

### Querying the log

[](#querying-the-log)

The behavior adds a `logEvents` relation to the owner model (newest first):

```
foreach ($order->logEvents as $log) {
    echo $log->event;         // INSERT | UPDATE | DELETE
    echo $log->created_at;    // timestamp
    print_r($log->dataArray); // payload decoded as PHP array, on any DB
}
```

Or query directly:

```
use lab37\logevent\models\LogEvent;

$logs = LogEvent::find()
    ->forEntity(Order::tableName(), $order->id)
    ->ofEvent(LogEvent::EVENT_UPDATE)
    ->ordered()
    ->all();
```

Tests
-----

[](#tests)

```
composer install
composer test
```

The suite runs against an in-memory SQLite database and also exercises the package migration.

License
-------

[](#license)

MIT. See [LICENSE](LICENSE).

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

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

Unknown

Total

1

Last Release

2d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/18093699?v=4)[Julio Guillermo Farra](/maintainers/juliofarra)[@juliofarra](https://github.com/juliofarra)

---

Tags

logAudityii2extensionBehavioractiverecordaudit-trail

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/juliofarra-yii2-logevent/health.svg)

```
[![Health](https://phpackages.com/badges/juliofarra-yii2-logevent/health.svg)](https://phpackages.com/packages/juliofarra-yii2-logevent)
```

###  Alternatives

[sammaye/yii2-audittrail

A port of audit trail

39414.9k](/packages/sammaye-yii2-audittrail)[lav45/yii2-activity-logger

Tools to store user activity log for Yii2

3459.5k](/packages/lav45-yii2-activity-logger)[kriss/yii2-log-reader

Yii2 log reader

1242.1k1](/packages/kriss-yii2-log-reader)

PHPackages © 2026

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