PHPackages                             elstc/cakephp-activity-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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. elstc/cakephp-activity-logger

ActiveCakephp-plugin[Logging &amp; Monitoring](/categories/logging)

elstc/cakephp-activity-logger
=============================

ActivityLogger plugin for CakePHP

v3.3.1(2mo ago)98.7k↓33.3%4[3 issues](https://github.com/elstc/cakephp-activity-logger/issues)MITPHPPHP &gt;=8.1CI passing

Since Jun 12Pushed 3mo ago3 watchersCompare

[ Source](https://github.com/elstc/cakephp-activity-logger)[ Packagist](https://packagist.org/packages/elstc/cakephp-activity-logger)[ RSS](/packages/elstc-cakephp-activity-logger/feed)WikiDiscussions cake5 Synced 1mo ago

READMEChangelog (10)Dependencies (14)Versions (35)Used By (0)

ActivityLogger plugin for CakePHP 5.x
=====================================

[](#activitylogger-plugin-for-cakephp-5x)

ActivityLogger plugin automatically logs database operations (create, update, delete) in CakePHP applications. It tracks who, when, and what was changed.

 [ ![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265) ](LICENSE.txt) [ ![Build Status](https://camo.githubusercontent.com/017bf0f8e7f5bc90fbc2cdc8b93f1e7d1a514aaef12dd1dc56f58a504fe431d5/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f656c7374632f63616b657068702d61637469766974792d6c6f676765722f63692e796d6c3f7374796c653d666c61742d737175617265) ](https://github.com/elstc/cakephp-activity-logger/actions) [ ![Codecov](https://camo.githubusercontent.com/bc942ce8898b2d1f49121f2b6ccc941d149efb2e1e4ce2c2d8055e95da429db3/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f656c7374632f63616b657068702d61637469766974792d6c6f676765722e7376673f7374796c653d666c61742d737175617265) ](https://codecov.io/gh/elstc/cakephp-activity-logger) [ ![Latest Stable Version](https://camo.githubusercontent.com/9e0025deca75f0b688435f450e06dd4803e94dd380e50d564a2f59883bad2032/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f656c7374632f63616b657068702d61637469766974792d6c6f676765722e7376673f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/elstc/cakephp-activity-logger)

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

[](#requirements)

- PHP 8.1 or higher
- CakePHP 5.0 or higher
- PDO extension
- JSON extension

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

[](#installation)

You can install this plugin into your CakePHP application using [composer](http://getcomposer.org).

The recommended way to install composer packages is:

```
composer require elstc/cakephp-activity-logger:^3.0

```

### Load plugin

[](#load-plugin)

Load the plugin by adding the following statement in your project's `src/Application.php`:

```
$this->addPlugin('Elastic/ActivityLogger');
```

### Create the activity\_logs table

[](#create-the-activity_logs-table)

Run migration command:

```
bin/cake migrations migrate -p Elastic/ActivityLogger

```

Usage
-----

[](#usage)

### Attach to Table

[](#attach-to-table)

Attach the ActivityLogger plugin to your table to enable automatic logging:

```
class ArticlesTable extends Table
{
    public function initialize(array $config): void
    {
        // ...

        $this->addBehavior('Elastic/ActivityLogger.Logger', [
            'scope' => [
                'Articles',
                'Authors',
            ],
        ]);
    }
}
```

### Basic Activity Logging

[](#basic-activity-logging)

#### Logging on create

[](#logging-on-create)

```
$article = $this->Articles->newEntity([ /* data */ ]);
$this->Articles->save($article);
// saved log
// [action='create', scope_model='Articles', scope_id=$article->id]
```

#### Logging on update

[](#logging-on-update)

```
$article = $this->Articles->patchEntity($article, [ /* update data */ ]);
$this->Articles->save($article);
// saved log
// [action='update', scope_model='Articles', scope_id=$article->id]
```

#### Logging on delete

[](#logging-on-delete)

```
$article = $this->Articles->get($id);
$this->Articles->delete($article);
// saved log
// [action='delete', scope_model='Articles', scope_id=$article->id]
```

### Activity Logging with Issuer

[](#activity-logging-with-issuer)

You can log information about the user who performed the operation:

```
$this->Articles->setLogIssuer($author); // Set issuer

$article = $this->Articles->newEntity([ /* data */ ]);
$this->Articles->save($article);

// saved log
// [action='create', scope_model='Articles', scope_id=$article->id, ...]
// and
// [action='create', scope_model='Authors', scope_id=$author->id, ...]
```

#### AutoIssuerMiddleware (Recommended for CakePHP 4.x+)

[](#autoissuermiddleware-recommended-for-cakephp-4x)

`AutoIssuerMiddleware` is a PSR-15 compliant middleware that provides automatic issuer setting for applications using the `Authorization` plugin. This middleware operates at the application level and processes authentication information early in the request lifecycle.

##### Installation and Configuration

[](#installation-and-configuration)

```
// In src/Application.php
use Elastic\ActivityLogger\Http\Middleware\AutoIssuerMiddleware;

class Application extends BaseApplication
{
    public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
    {
        $middlewareQueue
            // ... other middleware
            ->add(new AuthenticationMiddleware($this))

            // Add AutoIssuerMiddleware AFTER authentication middleware
            ->add(new AutoIssuerMiddleware([
                'userModel' => 'Users',           // User model name (default: 'Users')
                'identityAttribute' => 'identity', // Request attribute name (default: 'identity')
            ]))

            // ... other middleware
            ->add(new RoutingMiddleware($this));

        return $middlewareQueue;
    }
}
```

##### Important Notes

[](#important-notes)

- **Middleware Order**: Always place AutoIssuerMiddleware AFTER authentication middleware

#### AutoIssuerComponent (Legacy Approach)

[](#autoissuercomponent-legacy-approach)

If you're using `Authorization` plugin or `AuthComponent`, the `AutoIssuerComponent` will automatically set the issuer to Tables:

```
// In AppController
class AppController extends Controller
{
    public function initialize(): void
    {
        // ...
        $this->loadComponent('Elastic/ActivityLogger.AutoIssuer', [
            'userModel' => 'Users',  // Specify user model name
        ]);
        // ...
    }
}
```

### Activity Logging with Scope

[](#activity-logging-with-scope)

You can log operations related to multiple models:

```
class CommentsTable extends Table
{
    public function initialize(array $config): void
    {
        // ...

        $this->addBehavior('Elastic/ActivityLogger.Logger', [
            'scope' => [
                'Articles',
                'Authors',
                'Users',
            ],
        ]);
    }
}
```

```
$this->Comments->setLogScope([$user, $article]); // Set scope

$comment = $this->Comments->newEntity([ /* data */ ]);
$this->Comments->save($comment);

// saved log
// [action='create', scope_model='Users', scope_id=$user->id, ...]
// and
// [action='create', scope_model='Articles', scope_id=$article->id, ...]
```

### Activity Logging with Custom Messages

[](#activity-logging-with-custom-messages)

You can use the `setLogMessageBuilder` method to generate custom messages for each log action:

```
class ArticlesTable extends Table
{
    public function initialize(array $config): void
    {
        // ...

        $this->addBehavior('Elastic/ActivityLogger.Logger', [
            'scope' => [
                'Articles',
                'Authors',
            ],
        ]);

        // Add message builder
        $this->setLogMessageBuilder(static function (ActivityLog $log, array $context) {
            if ($log->message !== null) {
               return $log->message;
            }

            $message = '';
            $object = $context['object'] ?: null;
            $issuer = $context['issuer'] ?: null;
            switch ($log->action) {
                case ActivityLog::ACTION_CREATE:
                    $message = sprintf('%3$s created article #%1$s: "%2$s"', $object->id, $object->title, $issuer->username);
                    break;
                case ActivityLog::ACTION_UPDATE:
                    $message = sprintf('%3$s updated article #%1$s: "%2$s"', $object->id, $object->title, $issuer->username);
                    break;
                case ActivityLog::ACTION_DELETE:
                    $message = sprintf('%3$s deleted article #%1$s: "%2$s"', $object->id, $object->title, $issuer->username);
                    break;
                default:
                    break;
            }

            return $message;
        });
    }
}
```

Alternatively, you can use `setLogMessage` before save/delete operations to set a log message:

```
$this->Articles->setLogMessage('Custom Message');
$this->Articles->save($entity);
// saved log
// [action='update', 'message' => 'Custom Message', ...]
```

### Save Custom Log

[](#save-custom-log)

You can also record your own activity logs:

```
$this->Articles->activityLog(\Psr\Log\LogLevel::NOTICE, 'Custom Message', [
  'action' => 'custom',
  'object' => $article,
]);

// saved log
// [action='custom', 'message' => 'Custom Message', scope_model='Articles', scope_id=$article->id, ...]
```

### Find Activity Logs

[](#find-activity-logs)

You can search recorded activity logs:

```
$logs = $this->Articles->find('activity', ['scope' => $article]);
```

Advanced Usage Examples
-----------------------

[](#advanced-usage-examples)

### Conditional Logging

[](#conditional-logging)

When you want to log only under certain conditions:

```
// Log only when specific fields are changed
if ($article->isDirty('status')) {
    $this->Articles->setLogMessage('Status was changed');
}
$this->Articles->save($article);
```

### Batch Processing with Logging

[](#batch-processing-with-logging)

During large data processing, you can temporarily disable logging:

```
// Temporarily disable logging
$behavior = $this->Authors->disableActivityLog();

// Batch processing
foreach ($articles as $article) {
    $this->Articles->save($article);
}

// Re-enable logging
$this->Articles->enableActivityLog();
```

Upgrading
---------

[](#upgrading)

### CakePHP 5.3+

[](#cakephp-53)

CakePHP 5.3 deprecated calling behavior methods directly on the Table class. To maintain backward compatibility with your existing code, add `LoggerTrait` to your Table classes:

```
use Elastic\ActivityLogger\Model\Table\LoggerTrait;

class ArticlesTable extends Table
{
    use LoggerTrait;

    public function initialize(array $config): void
    {
        $this->addBehavior('Elastic/ActivityLogger.Logger');
    }
}
```

With this trait, you can continue using the familiar method calls:

```
// These methods work as before
$this->Articles->setLogScope($article);
$this->Articles->setLogIssuer($user);
$this->Articles->setLogMessage('Custom message');
```

Without the trait, you need to call methods through the behavior:

```
// Without LoggerTrait (CakePHP 5.3+ recommended pattern)
$this->Articles->getBehavior('Logger')->setLogScope($article);
```

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

**Q: Logs are not being recorded**

A: Please check the following:

- Whether migrations have been executed
- Whether the Behavior is properly attached
- Whether there are any database connection issues

**Q: Issuer information is not being recorded**

A: Please check the following:

- If using AutoIssuerMiddleware: Ensure it's placed AFTER authentication middleware in the middleware queue
- If using AutoIssuerComponent: Verify it's loaded in your controller's initialize() method
- Check if `setLogIssuer()` is manually set when needed
- Verify the user model configuration matches your application's user table

**Q: AutoIssuerMiddleware vs AutoIssuerComponent - Which should I use?**

A:

- **Use AutoIssuerMiddleware** (Recommended for CakePHP 4.x+):

    - For new applications
    - When you need application-wide issuer tracking
    - For better performance and cleaner architecture
    - When using PSR-15 middleware stack
- **Use AutoIssuerComponent**:

    - For legacy applications or CakePHP 3.x
    - When you need controller-specific issuer handling
    - For backward compatibility

**Q: Is there any performance impact?**

A:

- AutoIssuerMiddleware has minimal performance impact as it processes once per request
- When handling large amounts of data, consider temporarily disabling logging as needed

**Q: The issuer is not set for dynamically loaded Tables**

A: The AutoIssuerMiddleware hooks into `Model.initialize` events. Ensure:

- The middleware is loaded before any Table access
- Tables are loaded through the TableLocator (not manually instantiated)
- The LoggerBehavior is attached to the Table

License
-------

[](#license)

MIT License. See [LICENSE.txt](LICENSE.txt) for details.

Contributing
------------

[](#contributing)

Bug reports and feature requests are welcome at [GitHub Issues](https://github.com/elstc/cakephp-activity-logger/issues).

Pull requests are also welcome. We recommend discussing large changes in an Issue first.

###  Health Score

55

—

FairBetter than 98% of packages

Maintenance76

Regular maintenance activity

Popularity31

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity83

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 95.7% 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 ~102 days

Recently: every ~66 days

Total

32

Last Release

77d ago

Major Versions

v1.5.2 → v2.0.0-rc42021-01-22

v1.5.3 → v2.0.0-rc52021-03-25

v1.6.0 → v2.0.0-rc62022-09-02

v2.1.0 → v3.0.02024-02-09

v2.2.0 → v3.3.02026-02-06

PHP version history (4 changes)v1.0.6PHP &gt;=5.4.16

v1.2.0PHP &gt;=5.6

v2.0.0-beta1PHP &gt;=7.2

v3.0.0PHP &gt;=8.1

### Community

Maintainers

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

---

Top Contributors

[![nojimage](https://avatars.githubusercontent.com/u/100564?v=4)](https://github.com/nojimage "nojimage (177 commits)")[![gringlas](https://avatars.githubusercontent.com/u/4557329?v=4)](https://github.com/gringlas "gringlas (5 commits)")[![elastic-inc](https://avatars.githubusercontent.com/u/276172?v=4)](https://github.com/elastic-inc "elastic-inc (3 commits)")

---

Tags

auditcakephpcakephp-pluginlogginguser-activity

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/elstc-cakephp-activity-logger/health.svg)

```
[![Health](https://phpackages.com/badges/elstc-cakephp-activity-logger/health.svg)](https://phpackages.com/packages/elstc-cakephp-activity-logger)
```

###  Alternatives

[sentry/sentry

PHP SDK for Sentry (http://sentry.io)

1.9k227.1M273](/packages/sentry-sentry)[rollbar/rollbar

Monitors errors and exceptions and reports them to Rollbar

33723.7M82](/packages/rollbar-rollbar)[illuminate/log

The Illuminate Log package.

6224.3M518](/packages/illuminate-log)[open-telemetry/sdk

SDK for OpenTelemetry PHP.

2222.9M248](/packages/open-telemetry-sdk)[open-telemetry/api

API for OpenTelemetry PHP.

1833.0M214](/packages/open-telemetry-api)[pagemachine/typo3-formlog

Form log for TYPO3

23225.3k6](/packages/pagemachine-typo3-formlog)

PHPackages © 2026

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