Skip to content

Commit

Permalink
Merge pull request #19 from digitalrisks/added-logger-to-service-prov…
Browse files Browse the repository at this point in the history
…ider

feat: Handle Logging output in app.
  • Loading branch information
Kani Robinson authored Nov 4, 2019
2 parents 5c70f4c + 92e7b28 commit 747421a
Show file tree
Hide file tree
Showing 8 changed files with 138 additions and 22 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,22 @@ class EventStoreServiceProvider extends EventStoreApplicationServiceProvider
});
}

/**
* Handle logging when event is triggered.
*
* @return void
*/
public function logger()
{
// This will setup the logger for when an event happens.
EventStore::logger();

// You can customise this by doing the following.
EventStore::logger(function ($event, $type) {
Log::info($event->getType());
});
}

/**
* Register the application services.
*/
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
},
"require-dev": {
"orchestra/testbench": "^4.0",
"phpunit/phpunit": "^8.0"
"phpunit/phpunit": "^8.0",
"timacdonald/log-fake": "^1.4"
},
"autoload": {
"psr-4": {
Expand Down
33 changes: 14 additions & 19 deletions src/Console/Commands/EventStoreWorker.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ private function processPersistentStream($eventStore, string $stream): void
$eventStore
->persistentSubscription($stream, config('eventstore.group'), $this->option('parallel') ?? 1)
->subscribe(function (AcknowledgeableEventRecord $event) {
$this->logEventStart($event, 'persistent');
try {
$this->dispatch($event);
$event->ack();
Expand All @@ -96,7 +95,6 @@ private function processVolatileStream($eventStore, string $stream): void
$eventStore
->volatileSubscription($stream)
->subscribe(function (EventRecord $event) {
$this->logEventStart($event, 'volatile');
try {
$this->dispatch($event);
} catch (\Exception $e) {
Expand All @@ -106,17 +104,6 @@ private function processVolatileStream($eventStore, string $stream): void
}, 'report');
}

protected function logEventStart(EventRecord $event, $type = '')
{
$url = parse_url(config('eventstore.http_url'));
$url = "{$url['scheme']}://{$url['host']}:{$url['port']}";

$stream = $event->getStreamId();
$number = $event->getNumber();

Log::info("{$url}/streams/{$stream}/{$number}", ['type' => $type]);
}

protected function dumpEvent(EventRecord $event)
{
dump([
Expand All @@ -141,23 +128,31 @@ protected function safeGetMetadata(EventRecord $event)

public function dispatch(EventRecord $eventRecord): void
{
$event = $this->makeSerializableEvent($eventRecord);
$logger = LaravelEventStore::$logger;
$serializedEvent = $payload = $this->makeSerializableEvent($eventRecord);
$event = $serializedEvent->getType();

if ($localEvent = $this->mapToLocalEvent($event)) {
event($localEvent);
} else {
event($event->getType(), $event);
if ($localEvent = $this->mapToLocalEvent($serializedEvent)) {
$event = $localEvent;
$payload = null;
}

$logger($serializedEvent, $event);
event($event, $payload);
}

private function makeSerializableEvent(EventRecord $event): JsonEventRecord
{
$data = new EventData();

$data->setEventId($event->getId());
$data->setEventType($event->getType());
$data->setCreatedEpoch($event->getCreated()->getTimestamp() * 1000);
$data->setEventNumber($event->getNumber());
$data->setData(json_encode($event->getData()));
$data->setEventStreamId($event->getStreamId());
$data->setMetadata(json_encode($this->safeGetMetadata($event)));
$data->setCreatedEpoch($event->getCreated()->getTimestamp() * 1000);


return new JsonEventRecord($data);
}
Expand Down
32 changes: 32 additions & 0 deletions src/EventStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace DigitalRisks\LaravelEventStore;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Event;

class EventStore
{
/**
Expand All @@ -11,6 +14,13 @@ class EventStore
*/
public static $eventToClass;

/**
* Variable for logger.
*
* @var callable
*/
public static $logger;

/**
* Set the event class based on current event key.
*
Expand All @@ -25,4 +35,26 @@ public static function eventToClass(?callable $callback = null)

static::$eventToClass = $callback;
}

/**
* Set the logger environment.
*
* @param callable $callback
* @return void
*/
public static function logger(?callable $callback = null)
{
$callback = $callback ?: function ($event, $type) {
$url = parse_url(config('eventstore.http_url'));
$url = "{$url['scheme']}://{$url['host']}:{$url['port']}/web/index.html#";
$type = $event->getType();
$stream = $event->getStreamId();
$number = $event->getNumber();
$hasListener = Event::hasListeners($type);

Log::info("{$url}/streams/{$stream}/{$number}", ['type' => $type, 'hasListeners' => $hasListener]);
};

static::$logger = $callback;
}
}
14 changes: 13 additions & 1 deletion src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ class ServiceProvider extends LaravelServiceProvider
*/
public function boot()
{
$this->eventClasses();
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../config/eventstore.php' => config_path('eventstore.php'),
Expand All @@ -29,6 +28,9 @@ public function boot()
]);
}

$this->eventClasses();
$this->logger();

Event::listen(ShouldBeStored::class, SendToEventStoreListener::class);
}

Expand All @@ -42,6 +44,16 @@ public function eventClasses()
EventStore::eventToClass();
}

/**
* Handle logging when event is triggered.
*
* @return void
*/
public function logger()
{
EventStore::logger();
}

/**
* Register the application services.
*/
Expand Down
3 changes: 2 additions & 1 deletion src/Tests/Traits/MakesEventRecords.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@

trait MakesEventRecords
{
public function makeEventRecord($type, $data, $metadata = [], $created = null)
public function makeEventRecord($type, $data, $metadata = [], $created = null, $stream = 'test-stream')
{
$event = new EventRecord();
$created = new Carbon($created);

$event->setEventType($type);
$event->setEventStreamId($stream);
$event->setCreatedEpoch($created->getTimestamp() * 1000);
$event->setData(json_encode($data));
$event->setMetadata(json_encode($metadata));
Expand Down
58 changes: 58 additions & 0 deletions tests/LoggerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

namespace DigitalRisks\LaravelEventStore\Tests;

use DigitalRisks\LaravelEventStore\Console\Commands\EventStoreWorker;
use DigitalRisks\LaravelEventStore\EventStore;
use DigitalRisks\LaravelEventStore\Tests\Fixtures\TestEvent;
use DigitalRisks\LaravelEventStore\Tests\Traits\MakesEventRecords;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use TiMacDonald\Log\LogFake;

class LoggerTest extends TestCase
{
use MakesEventRecords;

public function test_it_logs_an_event()
{
// Arrange.
Log::swap(new LogFake);

$worker = resolve(EventStoreWorker::class);
$event = $this->makeEventRecord('test_event', ['hello' => 'world']);

// Act.
$worker->dispatch($event);

// Assert.
Log::assertLogged('info', function ($message, $context) {
$this->assertStringContainsString("/streams/test-stream/0", $message);
$this->assertEquals(['type' => 'test_event', 'hasListeners' => false], $context);

return true;
});
}

public function test_it_logs_an_event_with_a_listener()
{
// Arrange.
Log::swap(new LogFake);

$worker = resolve(EventStoreWorker::class);
$event = $this->makeEventRecord('test_event', ['hello' => 'world']);
Event::listen('test_event', function () {
});

// Act.
$worker->dispatch($event);

// Assert.
Log::assertLogged('info', function ($message, $context) {
$this->assertStringContainsString("/streams/test-stream/0", $message);
$this->assertEquals(['type' => 'test_event', 'hasListeners' => true], $context);

return true;
});
}
}
1 change: 1 addition & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class TestCase extends Orchestra
protected function getPackageProviders($app)
{
EventStore::eventToClass();
EventStore::logger();

return [
ServiceProvider::class,
Expand Down

0 comments on commit 747421a

Please sign in to comment.