PHPackages                             rogermaciel/audit-log - 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. rogermaciel/audit-log

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

rogermaciel/audit-log
=====================

Flexible and rock solid audit log tracking plugin for cakephp

1.0(6y ago)05MITPHPPHP &gt;=7.0.0

Since Nov 26Pushed 6y ago1 watchersCompare

[ Source](https://github.com/rogermaciel/audit-log)[ Packagist](https://packagist.org/packages/rogermaciel/audit-log)[ RSS](/packages/rogermaciel-audit-log/feed)WikiDiscussions master Synced today

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

AuditLog plugin for CakePHP
===========================

[](#auditlog-plugin-for-cakephp)

[![Build Status](https://camo.githubusercontent.com/88584e2681a6eda4d98bd4c485f934e5bea730d00cd5cc6213e5126dfc10959c/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6c6f72656e7a6f2f61756469742d73746173682f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/lorenzo/audit-stash)[![StyleCI Status](https://camo.githubusercontent.com/4af0f5e9fa37650e1dc698c146ff4132c0fb3580ceac271129cc28e1415f3a8d/68747470733a2f2f7374796c6563692e696f2f7265706f732f33393235303038342f736869656c64)](https://styleci.io/repos/39250084)[![Coverage Status](https://camo.githubusercontent.com/f1ab2c42f9ab15714936d44142eab741ba637af0a84d26fc4e83b84e9080f7f2/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6c6f72656e7a6f2f61756469742d73746173682f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/github/lorenzo/audit-stash)[![Total Downloads](https://camo.githubusercontent.com/bd718b61dc869cb9dedeb9d78d3d4e006dd1a793a758a293a22ddc4aa4366e64/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6c6f72656e7a6f2f61756469742d73746173682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/lorenzo/audit-stash)[![License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](LICENSE.txt)

This plugin implements an "audit trail" for any of your Table classes in your application, that is, the ability of recording any creation, modification or delete of the entities of any particular table.

By default, this plugin stores the audit logs into [Elasticsearch](https://www.elastic.co/products/elasticsearch), as we have found that it is a fantastic storage engine for append-only streams of data and provides really powerful features for finding changes in the historic data.

Even though we suggest storing the logs in Elasticsearch, this plugin is generic enough so you can implement your own persisting strategies, if so you wish.

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

[](#installation)

You can install this plugin into your CakePHP application using [composer](http://getcomposer.org) and executing the following lines in the root of your application.

```
composer require rogermaciel/cakephp-auditlog
bin/cake plugin load AuditLog

```

For using the default storage engine (ElasticSearch) you need to install the official `elastic-search` plugin, by executing the following lines:

```
composer require cakephp/elastic-search
bin/cake plugin load Cake/ElasticSearch

```

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

[](#configuration)

### Elastic Search

[](#elastic-search)

You now need to add the datasource configuration to your `config/app.php` file:

```
'Datasources' => [
    'auditlog_elastic' => [
        'className' => 'Cake\ElasticSearch\Datasource\Connection',
        'driver' => 'Cake\ElasticSearch\Datasource\Connection',
        'host' => '127.0.0.1', // server where elasticsearch is running
        'port' => 9200
    ],
    ...
]
```

This is the most basic setup, it will use a single index for storing all the data. If you prefer to use a different index for each day (like logstash does), use the following configuration:

```
'Datasources' => [
    'auditlog_elastic' => [
        'className' => 'Cake\ElasticSearch\Datasource\Connection',
        'driver' => 'Cake\ElasticSearch\Datasource\Connection',
        'host' => '127.0.0.1', // server where elasticsearch is running
        'port' => 9200
    ],
    ...
]
```

The added `%s` will be used as a placeholder for the day of the year. **Using an index per day is strongly recommended.**

### Tables / Regular Databases

[](#tables--regular-databases)

If you want to use a regular database, respectively an engine that can be used via the CakePHP ORM API, then you can use the table persister that ships with this plugin.

To do so you need to configure the `AuditLog.persister` option accordingly. In your `config/app.php` file add the following configuration:

```
'AuditLog' => [
    'persister' => 'AuditLog\Persister\TablePersister'
]
```

The plugin will then by default try to store the logs in a table named `audit_logs`, via a table class with the alias `AuditLogs`, which you could create/overwrite in your application if you need.

You can find a migration in the `config/migration` folder of this plugin which you can apply to your database, this will add a table named `audit_logs` with all the default columns - alternatively create the table manually. After that you can bake the corresponding table class.

```
bin/cake migrations migrate -p AuditLog -t 20171018185609
bin/cake bake model AuditLogs

```

#### Table persister configuration

[](#table-persister-configuration)

The table persister supports various configuration options, please refer to [its API documentation](/src/Persister/TablePersister.php) for further information. Generally configuration can be applied via its `config()` (or `setConfig()`) method:

```
$this->addBehavior('AuditLog.AuditLog');
$this->behaviors()->get('AuditLog')->persister()->config([
    'extractMetaFields' => [
        'user.id' => 'user_id'
    ]
]);
```

Using AuditLog
--------------

[](#using-auditlog)

Enabling the Audit Log in any of your table classes is as simple as adding a behavior in the `initialize()` function:

```
class ArticlesTable extends Table
{
    public function initialize(array $config = [] )
    {
        ...
        $this->addBehavior('AuditLog.AuditLog');
    }
}
```

When using the `Elasticserch` persister, it is recommended that you tell Elasticsearch about the schema of your table. You can do this automatically by executing the following command:

```
bin/cake elastic_mapping Articles

```

If you are using one index per day, save yourself some time and add the `--use-templates` option. This will create a schema template so any new index will inherit this configuration:

```
bin/cake elastic_mapping Articles --use-templates

```

Remember to execute the command line each time you change the schema of your table!

### Configuring The Behavior

[](#configuring-the-behavior)

The `AuditLog` behavior can be configured to ignore certain fields of your table, by default it ignores the `created` and `modified` fields:

```
class ArticlesTable extends Table
{
    public function initialize(array $config = [] )
    {
        ...
        $this->addBehavior('AuditLog.AuditLog', [
            'blacklist' => ['created', 'modified', 'another_field_name']
        ]);
    }
}
```

If you prefer, you can use a `whitelist` instead. This means that only the fields listed in that array will be tracked by the behavior:

```
    public function initialize(array $config = [] )
    {
        ...
        $this->addBehavior('AuditLog.AuditLog', [
            'whitelist' => ['title', 'description', 'author_id']
        ]);
    }
```

### Storing The Logged In User

[](#storing-the-logged-in-user)

It is often useful to store the identifier of the user that is triggering the changes in a certain table. For this purpose, `AuditLog`provides the `RequestMetadata` listener class, that is capable of storing the current URL, IP and logged in user. You need to add this listener to your application in the `AppController::beforeFilter()` method:

```
use AuditLog\Meta\RequestMetadata;
...

class AppController extends Controller
{
    public function beforeFilter(Event $event)
    {
        ...
        $eventManager = $this->loadModel()->eventManager();
        $eventManager->on(new RequestMetadata($this->request, $this->Auth->user('id')));
    }
}
```

The above code assumes that you will trigger the table operations from the controller, using the default Table class for the controller. If you plan to use other Table classes for saving or deleting inside the same controller, it is advised that you attach the listener globally:

```
use AuditLog\Meta\RequestMetadata;
use Cake\Event\EventManager;
...

class AppController extends Controller
{
    public function beforeFilter(Event $event)
    {
        ...
        EventManager::instance()->on(new RequestMetadata($this->request, $this->Auth->user('id')));
    }
}
```

### Storing Extra Information In Logs

[](#storing-extra-information-in-logs)

`AuditLog` is also capable of storing arbitrary data for each of the logged events. You can use the `ApplicationMetadata` listener or create your own. If you choose to use `ApplicationMetadata`, your logs will contain the `app_name` key stored and any extra information your may have provided. You can configure this listener anywhere in your application, such as the `bootstrap.php` file or, again, directly in your AppController.

```
use AuditLog\Meta\ApplicationMetadata;
use Cake\Event\EventManager;

EventManager::instance()->on(new ApplicationMetadata('my_blog_app', [
    'server' => $theServerID,
    'extra' => $somExtraInformation,
    'moon_phase' => $currentMoonPhase
]));
```

Implementing your own metadata listeners is as simple as attaching the listener to the `AuditLog.beforeLog` event. For example:

```
EventManager::instance()->on('AuditLog.beforeLog', function ($event, array $logs) {
    foreach ($logs as $event) {
        $event->setMetaInfo($event->getMetaInfo() + ['extra' => 'This is extra data to be stored']);
    }
});
```

### Implementing Your Own Persister Strategies

[](#implementing-your-own-persister-strategies)

There are valid reasons for wanting to use a different persist engine for your audit logs. Luckily, this plugin allows you to implement your own storage engines. It is as simple as implementing the `PersisterInterface` interface:

```
use AuditLog\PersisterInterface;

class MyPersister implements PersisterInterface
{
    public function logEvents(array $auditLogs)
    {
        foreach ($auditLogs as $log) {
            $eventType = $log->getEventType();
            $data = [
                'timestamp' => $log->getTimestamp(),
                'transaction' => $log->getTransactionId(),
                'type' => $log->getEventType(),
                'primary_key' => $log->getId(),
                'source' => $log->getSourceName(),
                'parent_source' => $log->getParentSourceName(),
                'original' => json_encode($log->getOriginal()),
                'changed' => $eventType === 'delete' ? null : json_encode($log->getChanged()),
                'meta' => json_encode($log->getMetaInfo())
            ];
            $storage = new MyStorage();
            $storage->save($data);
        }
    }
}
```

Finally, you need to configure `AuditLog` to use your new persister. In the `config/app.php` file add the following lines:

```
'AuditLog' => [
    'persister' => 'App\Namespace\For\Your\Persister'
]
```

or if you are using as standalone via

```
\Cake\Core\Configure::write('AuditLog.persister', 'App\Namespace\For\Your\DatabasePersister');
```

The configuration contains the fully namespaced class name of your persister.

### Working With Transactional Queries

[](#working-with-transactional-queries)

Occasionally, you may want to wrap a number of database changes in a transaction, so that it can be rolled back if one part of the process fails. In order to create audit logs during a transaction, some additional setup is required. First create the file `src/Model/Audit/AuditTrail.php` with the following:

```
