Skip to content

Commit e42891f

Browse files
committed
🚏Make Log save event queueable. Add timestamp, since some Laravel model builder functions depend on them <- timestamps added to DB table so migration needs to be re-run or created_at and updated_at needs to be added manually.
1 parent a9e9e64 commit e42891f

File tree

9 files changed

+139
-43
lines changed

9 files changed

+139
-43
lines changed

readme.md

Lines changed: 39 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
Custom Larvel 5.6+ Log channel handler that can store log events to SQL or MongoDB databases.
1010
Uses Laravel native logging functionality.
1111

12-
### Installation
12+
## Installation
1313
```
1414
require danielme85/laravel-log-to-db
1515
```
@@ -19,7 +19,7 @@ If you are going to be using SQL database server to store log events you would n
1919
php artisan migrate
2020
```
2121

22-
### Configuration
22+
## Configuration
2323
Starting with Laravel 5.6 you will have a new settings file: "config/logging.php".
2424
You will need to add an array under 'channels' for Log-to-DB here like so:
2525
```php
@@ -46,7 +46,7 @@ You will need to add an array under 'channels' for Log-to-DB here like so:
4646
More info about some of these options: https://laravel.com/docs/5.6/logging#customizing-monolog-for-channels
4747

4848
There are some default settings and more information about configuring the logger in the 'logtodb.php' config file.
49-
This can be copied to your project so you can edit it with the vendor publish command.
49+
This could be copied to your project if you would like edit it with the vendor publish command.
5050
```
5151
php artisan vendor:publish
5252
```
@@ -58,6 +58,42 @@ Log::channel('mongodb')->info("This thing just happened");
5858
```
5959
This logger works the same as any other across Laravel, for example you can add it to a stack.
6060
You can log multiple levels to multiple DB connections... the possibilities are ENDLESS! 😎
61+
62+
#### Log Worker Queue
63+
It might be a good idea to save the log events with a Queue Worker. This way your server does not have to wait for
64+
the save process to finish. You would have to configure the Laravel Queue settings and run the Queue listener.
65+
https://laravel.com/docs/5.6/queues#running-the-queue-worker
66+
67+
## Usage
68+
Since this is a custom log channel for Laravel, all "standard" ways of generating log events etc should work with
69+
the Laravel Log Facade. See https://laravel.com/docs/5.6/logging for more information.
70+
71+
#### Fetching Logs
72+
The logging by this channel is done trough the Eloquent Model builder.
73+
LogToDB::model($channel, $connection, $collection);
74+
You can skip all function variables and the default settings from the config/logtodb.php will be used.
75+
```php
76+
$model = LogToDB::model();
77+
$model->all(); //All logs for defualt channel/connection
78+
```
79+
80+
Some more examples of getting logs
81+
```php
82+
$logs = LogToDB::model()->all();
83+
$logs = LogToDB::model()->where('id' = $id)->first();
84+
```
85+
86+
When getting logs for specific channel or DB connection and collection you can either use the channel name matching
87+
config/logging.php or connection name from config/databases.php. You can also specify collection/table name if needed as
88+
the third function variable when fetching the model.
89+
```php
90+
$logsFromDefault = LogDB::model()->all();
91+
$logsFromChannel = LogDB::model('database')->all();
92+
$logsFromMysql = LogToDB::model(null, 'mysql')->all();
93+
$logsFromMongoDB = LogToDB::model(null, 'mongodb', 'log')->all();
94+
```
95+
96+
##### Advanced /config/logging.php example
6197
```php
6298
'default' => env('LOG_CHANNEL', 'stack'),
6399

@@ -90,33 +126,4 @@ You can log multiple levels to multiple DB connections... the possibilities are
90126
],
91127
//....
92128
]
93-
```
94-
95-
### Usage
96-
Since this is a custom log channel for Laravel, all "standard" ways of generating log events etc should work with
97-
the Laravel Log Facade. See https://laravel.com/docs/5.6/logging for more information.
98-
99-
#### Fetching Logs
100-
The logging by this channel is done trough the Eloquent Model builder.
101-
LogToDB::model($channel, $connection, $collection);
102-
You can skip all function variables and the default settings from the config/logtodb.php will be used.
103-
```php
104-
$model = LogToDB::model();
105-
$model->all(); //All logs for defualt channel/connection
106-
```
107-
108-
Some more examples of getting logs
109-
```php
110-
$logs = LogToDB::model()->all();
111-
$logs = LogToDB::model()->where('id' = $id)->first();
112-
```
113-
114-
When getting logs for specific channel or DB connection and collection you can either use the channel name matching
115-
config/logging.php or connection name from config/databases.php. You can also specify collection/table name if needed as
116-
the third function variable when fetching the model.
117-
```php
118-
$logsFromDefault = LogDB::model()->all();
119-
$logsFromChannel = LogDB::model('database')->all();
120-
$logsFromMysql = LogToDB::model(null, 'mysql')->all();
121-
$logsFromMongoDB = LogToDB::model(null, 'mongodb', 'log')->all();
122129
```

src/Jobs/SaveNewLogEvent.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
namespace danielme85\LaravelLogToDB\Jobs;
4+
5+
6+
use danielme85\LaravelLogToDB\Models\DBLog;
7+
use danielme85\LaravelLogToDB\Models\DBLogMongoDB;
8+
use Illuminate\Bus\Queueable;
9+
use Illuminate\Queue\SerializesModels;
10+
use Illuminate\Queue\InteractsWithQueue;
11+
use Illuminate\Contracts\Queue\ShouldQueue;
12+
use Illuminate\Foundation\Bus\Dispatchable;
13+
14+
class SaveNewLogEvent implements ShouldQueue
15+
{
16+
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
17+
18+
protected $log;
19+
20+
/**
21+
* Create a new job instance.
22+
*
23+
* @param DBLog | DBLogMongoDB $log
24+
* @return void
25+
*/
26+
public function __construct($log)
27+
{
28+
$this->log = $log;
29+
}
30+
31+
/**
32+
* Execute the job.
33+
*
34+
* @return void
35+
*/
36+
public function handle()
37+
{
38+
$this->log->save();
39+
}
40+
}

src/LogToDB.php

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
<?php
22

33
namespace danielme85\LaravelLogToDB;
4+
use danielme85\LaravelLogToDB\Jobs\SaveNewLogEvent;
5+
use danielme85\LaravelLogToDB\Models\DBLog;
6+
use danielme85\LaravelLogToDB\Models\DBLogMongoDB;
47

58
/**
69
* Class LogToDb
@@ -34,6 +37,10 @@ class LogToDB
3437
* @var string
3538
*/
3639
public $collection;
40+
41+
public $saveWithQueue;
42+
43+
3744
/**
3845
* The DB config details
3946
* @var null
@@ -65,6 +72,9 @@ function __construct($channelConnection = null, $collection = null, $detailed =
6572
if (isset($config['max_rows'])) {
6673
$this->maxRows = (int)$config['max_rows'];
6774
}
75+
if (isset($config['queue_db_saves'])) {
76+
$this->saveWithQueue = $config['queue_db_saves'];
77+
}
6878
}
6979

7080
//Set config based on specified config from the Log handler
@@ -204,11 +214,21 @@ public function newFromMonolog(array $record) : self
204214
}
205215
$log->unix_time = time();
206216

207-
if ($log->save()) {
208-
if (!empty($this->maxRows)) {
209-
$this->removeOldestIfMaxRows();
217+
if (!empty($this->saveWithQueue)) {
218+
if(dispatch(new SaveNewLogEvent($log))->onQueue($this->saveWithQueue)) {
219+
if (!empty($this->maxRows)) {
220+
$this->removeOldestIfMaxRows();
221+
}
210222
}
211223
}
224+
else {
225+
if ($log->save()) {
226+
if (!empty($this->maxRows)) {
227+
$this->removeOldestIfMaxRows();
228+
}
229+
}
230+
}
231+
212232

213233
return $this;
214234
}

src/DBLog.php renamed to src/Models/DBLog.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<?php
22

3-
namespace danielme85\LaravelLogToDB;
3+
namespace danielme85\LaravelLogToDB\Models;
44

55
use Illuminate\Database\Eloquent\Model;
66

@@ -13,7 +13,6 @@ class DBLog extends Model
1313
{
1414
use LogToDbCreateObject;
1515

16-
public $timestamps = false;
1716
protected $connection;
1817
protected $table;
1918

src/DBLogMongoDB.php renamed to src/Models/DBLogMongoDB.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<?php
22

3-
namespace danielme85\LaravelLogToDB;
3+
namespace danielme85\LaravelLogToDB\Models;
44

55
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
66

@@ -13,7 +13,6 @@ class DBLogMongoDB extends Eloquent
1313
{
1414
use LogToDbCreateObject;
1515

16-
public $timestamps = false;
1716
protected $connection;
1817
protected $collection;
1918

src/LogToDbCreateObject.php renamed to src/Models/LogToDbCreateObject.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<?php
22

3-
namespace danielme85\LaravelLogToDB;
3+
namespace danielme85\LaravelLogToDB\Models;
44

55
/**
66
* Trait LogToDbCreateObject

src/config/logtodb.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,17 @@
6262
| 'max_rows' => false for no limit.
6363
*/
6464
'max_rows' => false,
65+
66+
/*
67+
|--------------------------------------------------------------------------
68+
| Name of Queue
69+
|--------------------------------------------------------------------------
70+
|
71+
| It might be a good idea to save log events with the queue helper.
72+
| This way the requests going to your sever does not have to wait for the Log
73+
| event to be saved. Set to a string like: 'queue_db_saves' => 'logWorker',
74+
| and make sure to run the queue worker.
75+
| https://laravel.com/docs/5.6/queues#running-the-queue-worker
76+
*/
77+
'queue_db_saves' => false,
6578
];

src/migrations/2018_08_11_003343_create_log_table.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ public function up()
2323
$table->text('datetime')->nullable();
2424
$table->longText('context')->nullable();
2525
$table->text('extra')->nullable();
26+
$table->timestamps();
2627
});
2728
}
2829

tests/LogToDbTest.php

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
use danielme85\LaravelLogToDB\LogToDB;
44
use Illuminate\Support\Facades\Log;
5+
use Illuminate\Support\Facades\Queue;
6+
use danielme85\LaravelLogToDB\Jobs\SaveNewLogEvent;
57

68
class LogToDbTest extends Orchestra\Testbench\TestCase
79
{
@@ -14,9 +16,6 @@ protected function setUp(): void
1416

1517
$this->artisan('migrate', ['--database' => 'mysql']);
1618

17-
$this->beforeApplicationDestroyed(function () {
18-
$this->artisan('migrate:rollback', ['--database' => 'mysql']);
19-
});
2019
}
2120
/**
2221
* Define environment setup.
@@ -149,6 +148,24 @@ public function testException() {
149148
$this->assertNotEmpty($log->context);
150149
}
151150

151+
/**
152+
* @group queue
153+
*
154+
*/
155+
public function testQueue() {
156+
Queue::fake();
157+
158+
config()->set('logtodb.queue_db_saves', 'saveLogJob');
159+
160+
Log::info("I'm supposed to be added to the queue...");
161+
Log::warning("I'm supposed to be added to the queue...");
162+
Log::debug("I'm supposed to be added to the queue...");
163+
164+
Queue::assertPushedOn(config('logtodb.queue_db_saves'), SaveNewLogEvent::class);
165+
Queue::assertPushed(SaveNewLogEvent::class, 6);
166+
167+
}
168+
152169
public function testCleanup() {
153170
LogToDB::model()::truncate();
154171
LogToDB::model('mongodb')::truncate();

0 commit comments

Comments
 (0)