Skip to content

Commit

Permalink
Merge pull request #10 from danielme85/dev
Browse files Browse the repository at this point in the history
Merge dev -> master, all green! ✅
  • Loading branch information
danielme85 authored Oct 4, 2019
2 parents 4974e8c + f5a5ed7 commit 17632d9
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 13 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
language: php
php:
- 7.2
- 7.3
services:
- mysql
- mongodb
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
}
],
"require": {
"php": ">=7.1",
"php": ">=7.2",
"illuminate/support": ">=5.6"
},
"require-dev": {
Expand Down
34 changes: 33 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
[![GitHub tag](https://img.shields.io/github/tag/danielme85/laravel-log-to-db.svg?style=flat-square)](https://github.com/danielme85/laravel-log-to-db)
[![Travis (.org)](https://img.shields.io/travis/danielme85/laravel-log-to-db.svg?style=flat-square)](https://travis-ci.org/danielme85/laravel-log-to-db)
[![Codecov](https://img.shields.io/codecov/c/github/danielme85/laravel-log-to-db.svg?style=flat-square)](https://codecov.io/gh/danielme85/laravel-log-to-db)
[![CodeFactor](https://www.codefactor.io/repository/github/danielme85/laravel-log-to-db/badge)](https://www.codefactor.io/repository/github/danielme85/laravel-log-to-db)

Custom Laravel 6/5.6+ Log channel handler that can store log events to SQL or MongoDB databases.
Uses Laravel native logging functionality.
Expand Down Expand Up @@ -50,7 +51,10 @@ You will need to add an array under 'channels' for Log-to-DB here like so:
'detailed' => true,
'queue' => false,
'queue_name' => '',
'queue_connection' => ''
'queue_connection' => '',
'processors' => [
//Monolog\Processor\HostnameProcessor::class
]
],
...
]
Expand All @@ -62,6 +66,8 @@ You will need to add an array under 'channels' for Log-to-DB here like so:
* connection = The DB connection from config/database.php to use (default: 'default').
* collection = The DB table or collection name. (Default: log).
* detailed = Store detailed log on Exceptions like stack-trace (default: true).
* processors = Array of additional processors. These will add additional info into the 'extra' field in the logged data.
[More information about processors](#processors)

More info about some of these options: https://laravel.com/docs/5.6/logging#customizing-monolog-for-channels

Expand Down Expand Up @@ -227,6 +233,32 @@ LogToDB::model()->removeOlderThen('2019-01-01');
LogToDB::model()->removeOlderThen('2019-01-01 23:00:00');
```

#### Processors
Monolog ships with a set of [processors](https://github.com/Seldaek/monolog/tree/master/src/Monolog/Processor), these will generate additional data and populate the 'extra' field.

You could also create your own custom processor, make sure they implement [Monolog\Processor\ProcessorInterface](https://github.com/Seldaek/monolog/blob/master/src/Monolog/Processor/ProcessorInterface.php).

##### Example of custom processor
```php
<?php

namespace App\CustomProcessors;

use Monolog\Processor\ProcessorInterface;

class PhpVersionProcessor implements ProcessorInterface {
/**
* @return array The processed record
*/
public function __invoke(array $record) {
$record['extra']['php_version'] = phpversion();

return $record;
}
}

```

#### Advanced /config/logging.php example
```php
'default' => env('LOG_CHANNEL', 'stack'),
Expand Down
11 changes: 6 additions & 5 deletions src/LogToDbCustomLoggingHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace danielme85\LaravelLogToDB;

use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;

/**
* Class LogToDbHandler
Expand Down Expand Up @@ -83,10 +82,8 @@ function __construct(array $config,
}
}


//Set the processors
if (!empty($processors))
{
if (!empty($processors)) {
foreach ($processors as $processor) {
$this->pushProcessor($processor);
}
Expand All @@ -112,7 +109,11 @@ protected function write(array $record): void
$this->saveWithQueueConnection);
$log->newFromMonolog($record);
} catch (\Exception $e) {

//We want ignore this exception for (at least) two reasons:
//1. Let's not ruin the whole app/request/job whatever is supposed to happen
// by this log write operation failing.
//2. There is a potential for an infinate loop of this log writer failing,
// then trying to write a log about the log failing :(
}
}
}
Expand Down
14 changes: 10 additions & 4 deletions src/LogToDbHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace danielme85\LaravelLogToDB;

use Monolog\Logger;
use Monolog\Processor\IntrospectionProcessor;

/**
* Class LogToDbHandler
Expand All @@ -20,9 +19,16 @@ class LogToDbHandler
*/
public function __invoke(array $config)
{
$processors = [
new IntrospectionProcessor()
];
$processors = [];

if (isset($config['processors']) && !empty($config['processors']) && is_array($config['processors'])) {
foreach ($config['processors'] as $processorName) {
if (class_exists($processorName)) {
$processors[] = new $processorName;
}
}
}

return new Logger($config['name'] ?? 'LogToDB',
[
new LogToDbCustomLoggingHandler($config, $processors)
Expand Down
29 changes: 29 additions & 0 deletions src/Processors/PhpVersionProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php
/**
* Created by PhpStorm.
* User: dmellum
* Date: 10/4/19
* Time: 1:53 PM
* ___ _ _ _ ___
* |_ _|_ __ | |_ ___ _ __ __| | ___ ___(_) __ _ _ __ |_ _|_ __ ___
* | || '_ \| __/ _ \ '__/ _` |/ _ \/ __| |/ _` | '_ \ | || '_ \ / __|
* | || | | | || __/ | | (_| | __/\__ \ | (_| | | | | | || | | | (__
* |___|_| |_|\__\___|_| \__,_|\___||___/_|\__, |_| |_| |___|_| |_|\___|
* |___/
*/

namespace danielme85\LaravelLogToDB\Processors;

use Monolog\Processor\ProcessorInterface;

class PhpVersionProcessor implements ProcessorInterface
{
/**
* @return array The processed record
*/
public function __invoke(array $record) {
$record['extra']['php_version'] = phpversion();

return $record;
}
}
55 changes: 53 additions & 2 deletions tests/LogToDbTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,21 @@ protected function getEnvironmentSetUp($app)
'via' => danielme85\LaravelLogToDB\LogToDbHandler::class,
'level' => 'debug',
'connection' => 'default',
'collection' => 'log'
'collection' => 'log',
'processors' => [
Monolog\Processor\HostnameProcessor::class,
danielme85\LaravelLogToDB\Processors\PhpVersionProcessor::class
]
],
'mongodb' => [
'driver' => 'custom',
'via' => danielme85\LaravelLogToDB\LogToDbHandler::class,
'level' => 'debug',
'connection' => 'mongodb',
'collection' => 'log'
'collection' => 'log',
'processors' => [
Monolog\Processor\HostnameProcessor::class
]
],
'limited' => [
'driver' => 'custom',
Expand Down Expand Up @@ -108,6 +115,10 @@ protected function getPackageProviders($app)
public function testClassInit() {
$test = new LogToDB();
$this->assertInstanceOf('danielme85\LaravelLogToDB\LogToDB', $test);

//Class works, now let's cleanup possible failed test
LogToDB::model()->truncate();
LogToDB::model('mongodb')->truncate();
}

/**
Expand All @@ -134,6 +145,19 @@ public function testLogLevels() {
$this->assertCount(8, $logReaderSpecific);
}

/**
* Check to see if processors are adding extra content.
*
* @group basic
*/
public function testProcessors()
{
$log = LogToDB::model()->orderBy('created_at', 'desc')->first()->toArray();
$this->assertNotEmpty($log['extra']);
$this->assertNotEmpty($log['extra']['php_version']);
$this->assertNotEmpty($log['extra']['hostname']);
}

/**
* Test logging to specific channels
*
Expand Down Expand Up @@ -188,6 +212,33 @@ public function testQueue() {
}

/**
* Test save new log event job
*
* @group job
*/
public function testSaveNewLogEventJob()
{
$logToDb = new LogToDB();
$record = [
'message' => 'job-test',
'context' => [],
'level' => 200,
'level_name' => 'INFO',
'channel' => 'local',
'datetime' => new Monolog\DateTimeImmutable(true),
'extra' => [],
'formatted' => "[2019-10-04T17:26:38.446827+00:00] local.INFO: test [] []\n"
];

$job = new SaveNewLogEvent($logToDb, $record);
$job->handle();

$this->assertNotEmpty($logToDb->model()->where('message', '=', 'job-test')->get());
}


/**
* Test model interaction
*
* @group model
*/
Expand Down

0 comments on commit 17632d9

Please sign in to comment.