Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
c4aa4b3
Feat: adapter and clickhouse adapter
lohanidamodar Dec 7, 2025
74af397
improvement with tenants
lohanidamodar Dec 7, 2025
52303ec
Refactor and fix test
lohanidamodar Dec 7, 2025
338fbea
Fix codeql
lohanidamodar Dec 7, 2025
241d940
remove unused
lohanidamodar Dec 7, 2025
250dc30
update docker compose
lohanidamodar Dec 7, 2025
22ab1fd
fix format
lohanidamodar Dec 7, 2025
a984108
Fix docker compose clickhouse healthcheck
lohanidamodar Dec 7, 2025
1c86da3
Test and fixes clickhouse adapter
lohanidamodar Dec 7, 2025
a658197
improve adapter
lohanidamodar Dec 7, 2025
c711f33
Refactor
lohanidamodar Dec 8, 2025
9a29463
codeql fix
lohanidamodar Dec 8, 2025
a19378e
Fix suggestions and security issues
lohanidamodar Dec 8, 2025
91ba188
remove id prefix
lohanidamodar Dec 8, 2025
db744cf
Further fixes
lohanidamodar Dec 8, 2025
7d1e588
Format
lohanidamodar Dec 8, 2025
5fd42bf
More suggestion fixes
lohanidamodar Dec 8, 2025
59225a1
wrong folder
lohanidamodar Dec 9, 2025
957a7a9
use docker compose wait
lohanidamodar Dec 9, 2025
7808825
updated return type
lohanidamodar Dec 9, 2025
03951d0
Fix test
lohanidamodar Dec 9, 2025
e806fa0
use batch delete
lohanidamodar Dec 9, 2025
97c1e0e
simplify conversion
lohanidamodar Dec 9, 2025
8e1211f
Fix comments and cleanup
lohanidamodar Dec 9, 2025
fd6b2dd
use validator
lohanidamodar Dec 9, 2025
5714e29
update to use time attribute
lohanidamodar Dec 9, 2025
7ac9f3b
fix type
lohanidamodar Dec 9, 2025
8cd0cec
fix params
lohanidamodar Dec 9, 2025
de10e8e
Fix create
lohanidamodar Dec 9, 2025
7251c3e
remove example file
lohanidamodar Dec 9, 2025
0e1920a
update readme
lohanidamodar Dec 9, 2025
db3d035
fix healthcheck
lohanidamodar Dec 9, 2025
257c1fc
fix escaping
lohanidamodar Dec 9, 2025
9ed6d87
Feat: add specialized methods with additional query params
lohanidamodar Dec 10, 2025
874de63
Update clickhouse to a safe approach
lohanidamodar Dec 10, 2025
2bb9159
Clickhouse specific tests
lohanidamodar Dec 10, 2025
c21f861
additional tests
lohanidamodar Dec 10, 2025
5ca5dd4
update datetime
lohanidamodar Dec 10, 2025
93c0fba
Feat: enhance log retrieval methods with optional filtering parameters
lohanidamodar Dec 10, 2025
5be0295
Dockerfile update
lohanidamodar Dec 10, 2025
d294584
remove unused import
lohanidamodar Dec 10, 2025
8a67e31
Update Dockerfile
lohanidamodar Dec 10, 2025
b04f8f8
Fix: use DateTime object in cleanup instead of string
lohanidamodar Dec 10, 2025
5cbab40
format
lohanidamodar Dec 10, 2025
711481b
fix date format
lohanidamodar Dec 10, 2025
d68d21d
Fix date time handling
lohanidamodar Dec 10, 2025
d72b523
fix codeql
lohanidamodar Dec 11, 2025
56584d2
remove duplicate
lohanidamodar Dec 11, 2025
e9a9c31
format time correctly in database adapter
lohanidamodar Dec 11, 2025
308d74b
Fix type check
lohanidamodar Dec 11, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
190 changes: 185 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,32 @@ Utopia framework audit library is simple and lite library for managing applicati

Although this library is part of the [Utopia Framework](https://github.com/utopia-php/framework) project it is dependency free, and can be used as standalone with any other PHP project or framework.

## Features

- **Adapter Pattern**: Support for multiple storage backends through adapters
- **Default Database Adapter**: Built-in support for utopia-php/database
- **Extensible**: Easy to create custom adapters for different storage solutions
- **Batch Operations**: Support for logging multiple events at once
- **Query Support**: Rich querying capabilities for retrieving logs

## Getting Started

Install using composer:
```bash
composer require utopia-php/audit
```

Init the audit object:
## Usage

### Using the Database Adapter (Default)

The simplest way to use Utopia Audit is with the built-in Database adapter:

```php
<?php

require_once __DIR__ . '/../../vendor/autoload.php';

use PDO;
use PDO;
use Utopia\Audit\Audit;
use Utopia\Cache\Cache;
Expand All @@ -36,7 +47,7 @@ $dbPass = '';
$dbPort = '3306';

$pdo = new PDO("mysql:host={$dbHost};port={$dbPort};charset=utf8mb4", $dbUser, $dbPass, [
PDO::ATTR_TIMEOUT => 3, // Seconds
PDO::ATTR_TIMEOUT => 3,
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
Expand All @@ -46,13 +57,35 @@ $pdo = new PDO("mysql:host={$dbHost};port={$dbPort};charset=utf8mb4", $dbUser, $

$cache = new Cache(new NoCache());

$database = new Database(new MySQL($pdo),$cache);
$database = new Database(new MySQL($pdo), $cache);
$database->setNamespace('namespace');

$audit = new Audit($database);
// Create audit instance with Database adapter
$audit = Audit::withDatabase($database);
$audit->setup();
```

### Using a Custom Adapter

You can create custom adapters by extending the `Utopia\Audit\Adapter` abstract class:

```php
<?php

use Utopia\Audit\Audit;
use Utopia\Audit\Adapter\Database as DatabaseAdapter;
use Utopia\Database\Database;

// Using the Database adapter directly
$adapter = new DatabaseAdapter($database);
$audit = Audit::withAdapter($adapter);

// Or using the static factory method
$audit = Audit::withDatabase($database);
```

### Basic Operations

**Create Log**

A simple example for logging a user action in the audit DB.
Expand Down Expand Up @@ -100,6 +133,153 @@ $logs = $audit->getLogsByResource(
); // Returns an array of all logs for the specific resource
```

**Batch Logging**

Log multiple events at once for better performance:

```php
use Utopia\Database\DateTime;

$events = [
[
'userId' => 'user-1',
'event' => 'create',
'resource' => 'database/document/1',
'userAgent' => 'Mozilla/5.0...',
'ip' => '127.0.0.1',
'location' => 'US',
'data' => ['key' => 'value'],
'timestamp' => DateTime::now()
],
[
'userId' => 'user-2',
'event' => 'update',
'resource' => 'database/document/2',
'userAgent' => 'Mozilla/5.0...',
'ip' => '192.168.1.1',
'location' => 'UK',
'data' => ['key' => 'value'],
'timestamp' => DateTime::now()
]
];

$documents = $audit->logBatch($events);
```

## Adapters

Utopia Audit uses an adapter pattern to support different storage backends. Currently available adapters:

### Database Adapter (Default)

The Database adapter uses [utopia-php/database](https://github.com/utopia-php/database) to store audit logs in a database.

**Supported Databases:**
- MySQL/MariaDB
- PostgreSQL
- MongoDB
- And all other databases supported by utopia-php/database

### ClickHouse Adapter

The ClickHouse adapter uses [ClickHouse](https://clickhouse.com/) for high-performance analytical queries on massive amounts of log data. It communicates with ClickHouse via HTTP interface using cURL.

**Features:**
- Optimized for analytical queries and aggregations
- Handles billions of log entries efficiently
- Column-oriented storage for fast queries
- Automatic partitioning by month
- Bloom filter indexes for fast lookups

**Usage:**

```php
<?php

use Utopia\Audit\Audit;
use Utopia\Audit\Adapter\ClickHouse;

// Create ClickHouse adapter
$adapter = new ClickHouse(
host: 'localhost',
database: 'audit',
username: 'default',
password: '',
port: 8123,
table: 'audit_logs'
);

$audit = Audit::withAdapter($adapter);
$audit->setup(); // Creates database and table

// Use as normal
$document = $audit->log(
userId: 'user-123',
event: 'document.create',
resource: 'database/document/1',
userAgent: 'Mozilla/5.0...',
ip: '127.0.0.1',
location: 'US',
data: ['key' => 'value']
);
```

**Performance Benefits:**
- Ideal for high-volume logging (millions of events per day)
- Fast aggregation queries (counts, analytics)
- Efficient storage with compression
- Automatic data partitioning and retention policies

### Creating Custom Adapters

To create a custom adapter, extend the `Utopia\Audit\Adapter` abstract class and implement all required methods:

```php
<?php

namespace MyApp\Audit;

use Utopia\Audit\Adapter;
use Utopia\Database\Document;

class CustomAdapter extends Adapter
{
public function getName(): string
{
return 'Custom';
}

public function setup(): void
{
// Initialize your storage backend
}

public function create(array $log): Document
{
// Store a single log entry
}

public function createBatch(array $logs): array
{
// Store multiple log entries
}

public function getByUser(string $userId, array $queries = []): array
{
// Retrieve logs by user ID
}

// Implement other required methods...
}
```

Then use your custom adapter:

```php
$adapter = new CustomAdapter();
$audit = Audit::withAdapter($adapter);
```

## System Requirements

Utopia Framework requires PHP 8.0 or later. We recommend using the latest PHP version whenever possible.
Expand Down
19 changes: 15 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@
"name": "utopia-php/audit",
"description": "A simple audit library to manage application users logs",
"type": "library",
"keywords": ["php","framework", "upf", "utopia", "audit"],
"keywords": [
"php",
"framework",
"upf",
"utopia",
"audit"
],
"license": "MIT",
"minimum-stability": "stable",
"scripts": {
Expand All @@ -11,14 +17,19 @@
"check": "./vendor/bin/phpstan analyse --level max src tests"
},
"autoload": {
"psr-4": {"Utopia\\Audit\\": "src/Audit"}
"psr-4": {
"Utopia\\Audit\\": "src/Audit"
}
},
"autoload-dev": {
"psr-4": {"Utopia\\Tests\\": "tests/Audit"}
"psr-4": {
"Utopia\\Tests\\": "tests/Audit"
}
},
"require": {
"php": ">=8.0",
"utopia-php/database": "4.*"
"utopia-php/database": "4.*",
"utopia-php/fetch": "^0.4.2"
},
"require-dev": {
"phpunit/phpunit": "9.*",
Expand Down
Loading
Loading