Skip to content

Commit

Permalink
Merge pull request #27 from yoeriboven/pruning
Browse files Browse the repository at this point in the history
Adds support for Laravel pruning
  • Loading branch information
yoeriboven authored Oct 9, 2024
2 parents 5342f66 + d31e0a6 commit d46c2a2
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ return [
'db' => [
'driver' => 'custom',
'via' => DatabaseLogger::class,
'connection' => env('LOG_DB_CONNECTION', env('DB_CONNECTION'))
'connection' => env('LOG_DB_CONNECTION', env('DB_CONNECTION')),
'days' => 7,
],
]
]
Expand Down
13 changes: 13 additions & 0 deletions src/Models/LogMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
namespace Yoeriboven\LaravelLogDb\Models;

use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use Illuminate\Database\Eloquent\MassPrunable;
use Illuminate\Database\Eloquent\Model;

class LogMessage extends Model
{
use MassPrunable;

/**
* The attributes that aren't mass assignable.
*
Expand Down Expand Up @@ -39,4 +42,14 @@ public function __construct(array $attributes = [])

$this->setConnection($connection);
}

/**
* Get the prunable model query.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function prunable()
{
return static::where('logged_at', '<=', now()->subDays(config('logging.channels.db.days')));
}
}
43 changes: 43 additions & 0 deletions tests/DatabaseLoggingTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Yoeriboven\LaravelLogDb\DatabaseLogger;
use Yoeriboven\LaravelLogDb\Models\LogMessage;
Expand Down Expand Up @@ -66,3 +67,45 @@
'message' => 'Test message',
], 'custom');
});

it('prunes old logs', function () {
config()->set('logging.channels.db.days', 7);

$message = LogMessage::create([
'level' => 200,
'level_name' => 'INFO',
'message' => 'Test message',
'logged_at' => now()->subDays(7),
'context' => [],
'extra' => [],
]);

Artisan::call('model:prune', [
'--model' => [
LogMessage::class,
],
]);

expect($message->fresh())->toBeNull();
});

it('doesnt prune new logs', function () {
config()->set('logging.channels.db.days', 7);

$message = LogMessage::create([
'level' => 200,
'level_name' => 'INFO',
'message' => 'Test message',
'logged_at' => now()->subDays(7)->addSecond(),
'context' => [],
'extra' => [],
]);

Artisan::call('model:prune', [
'--model' => [
LogMessage::class,
],
]);

expect($message->fresh())->not->toBeNull();
});

0 comments on commit d46c2a2

Please sign in to comment.