Skip to content

Commit

Permalink
Merge pull request #41 from arnidan/laravel-10
Browse files Browse the repository at this point in the history
Laravel 10 & graylog2/gelf-php 2 compatility
  • Loading branch information
hedii authored Feb 18, 2023
2 parents 4310f35 + a2bd432 commit 2a4f42d
Show file tree
Hide file tree
Showing 9 changed files with 123 additions and 78 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
php-versions: [ '8.0', '8.1' ]
php-versions: [ '8.1', '8.2' ]
name: Testing on PHP ${{ matrix.php-versions }}
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
extensions: mbstring,bcmath
tools: phpunit,composer
tools: composer
- name: Install dependencies
run: composer install --quiet --no-ansi --no-interaction --no-scripts --no-progress
- name: Run tests
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
/vendor
composer.lock
.phpunit.result.cache
.phpunit.cache
36 changes: 18 additions & 18 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
# The MIT License (MIT)

Copyright (c) 2020 Hedi Chaibi <[email protected]>
Copyright (c) Hedi Chaibi

> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
19 changes: 10 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@
[![License](https://poser.pugx.org/hedii/laravel-gelf-logger/license)](//packagist.org/packages/hedii/laravel-gelf-logger)
[![Latest Stable Version](https://poser.pugx.org/hedii/laravel-gelf-logger/v)](//packagist.org/packages/hedii/laravel-gelf-logger)

| **Laravel** | **laravel-gelf-logger** |
|---|---|
| 5.6 | ^3.0 |
| 5.8 | ^3.1 |
| 6.0 | ^4.0 |
| 7.0 | ^5.0 |
| 8.0 | ^5.3 |
| 8.0 | ^6.0 (with php 8) |
| 9.0 | ^7.0 |
| **Laravel** | **laravel-gelf-logger** |
|-------------|-------------------------|
| 5.6 | ^3.0 |
| 5.8 | ^3.1 |
| 6.0 | ^4.0 |
| 7.0 | ^5.0 |
| 8.0 | ^5.3 |
| 8.0 | ^6.0 (with php 8) |
| 9.0 | ^7.0 |
| 10.0 | ^8.0 |

A package to send [gelf](http://docs.graylog.org/en/2.1/pages/gelf.html) logs to a gelf compatible backend like graylog. It is a Laravel wrapper for [bzikarsky/gelf-php](https://github.com/bzikarsky/gelf-php) package.

Expand Down
8 changes: 4 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@
"source": "https://github.com/hedii/laravel-gelf-logger"
},
"require": {
"php": "^8.0",
"graylog2/gelf-php": "^1.7",
"illuminate/log": "^9.0"
"php": "^8.1",
"graylog2/gelf-php": "^2.0",
"illuminate/log": "^10.0"
},
"require-dev": {
"orchestra/testbench": "^7.0"
"orchestra/testbench": "^8.0"
},
"autoload": {
"psr-4": {
Expand Down
7 changes: 4 additions & 3 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
colors="true"
stopOnFailure="true">
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
<testsuite name="Laravel Gelf Logger Test Suite">
<directory suffix="Test.php">./tests/</directory>
Expand Down
60 changes: 44 additions & 16 deletions src/GelfLoggerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,26 +25,28 @@ public function __construct(protected Container $app)

public function __invoke(array $config): Logger
{
$config = $this->parseConfig($config);

$transport = $this->getTransport(
$config['transport'] ?? 'udp',
$config['host'] ?? '127.0.0.1',
$config['port'] ?? 12201,
$config['path'] ?? null,
$this->enableSsl($config) ? $this->sslOptions($config['ssl_options'] ?? null) : null
$config['transport'],
$config['host'],
$config['port'],
$config['path'],
$this->enableSsl($config) ? $this->sslOptions($config['ssl_options']) : null
);

if ($config['ignore_error'] ?? true) {
if ($config['ignore_error']) {
$transport = new IgnoreErrorTransportWrapper($transport);
}

$handler = new GelfHandler(new Publisher($transport), $this->level($config));

$handler->setFormatter(
new GelfMessageFormatter(
$config['system_name'] ?? null,
$config['extra_prefix'] ?? null,
$config['context_prefix'] ?? '',
$config['max_length'] ?? null
$config['system_name'],
$config['extra_prefix'],
$config['context_prefix'],
$config['max_length']
)
);

Expand All @@ -55,6 +57,30 @@ public function __invoke(array $config): Logger
return new Logger($this->parseChannel($config), [$handler]);
}

protected function parseConfig(array $config): array
{
$config['transport'] ??= 'udp';
$config['host'] ??= '127.0.0.1';
$config['port'] ??= 12201;
$config['path'] ??= null;
$config['system_name'] ??= null;
$config['extra_prefix'] ??= null;
$config['context_prefix'] ??= '';
$config['max_length'] ??= null;
$config['ignore_error'] ??= true;
$config['ssl'] ??= false;
$config['ssl_options'] ??= null;

if ($config['ssl_options']) {
$config['ssl_options']['verify_peer'] ??= true;
$config['ssl_options']['ca_file'] ??= null;
$config['ssl_options']['ciphers'] ??= null;
$config['ssl_options']['allow_self_signed'] ??= false;
}

return $config;
}

protected function getTransport(
string $transport,
string $host,
Expand All @@ -64,7 +90,9 @@ protected function getTransport(
): AbstractTransport {
return match (strtolower($transport)) {
'tcp' => new TcpTransport($host, $port, $sslOptions),
'http' => new HttpTransport($host, $port, $path ?? HttpTransport::DEFAULT_PATH, $sslOptions),
'http' => $path
? new HttpTransport($host, $port, $path, $sslOptions)
: new HttpTransport($host, $port, sslOptions: $sslOptions),
default => new UdpTransport($host, $port),
};
}
Expand All @@ -75,7 +103,7 @@ protected function enableSsl(array $config): bool
return false;
}

return $config['ssl'] ?? false;
return $config['ssl'];
}

protected function sslOptions(?array $sslConfig = null): SslOptions
Expand All @@ -86,10 +114,10 @@ protected function sslOptions(?array $sslConfig = null): SslOptions
return $sslOptions;
}

$sslOptions->setVerifyPeer($sslConfig['verify_peer'] ?? true);
$sslOptions->setCaFile($sslConfig['ca_file'] ?? null);
$sslOptions->setCiphers($sslConfig['ciphers'] ?? null);
$sslOptions->setAllowSelfSigned($sslConfig['allow_self_signed'] ?? false);
$sslOptions->setVerifyPeer($sslConfig['verify_peer']);
$sslOptions->setCaFile($sslConfig['ca_file']);
$sslOptions->setCiphers($sslConfig['ciphers']);
$sslOptions->setAllowSelfSigned($sslConfig['allow_self_signed']);

return $sslOptions;
}
Expand Down
16 changes: 12 additions & 4 deletions tests/GelfLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
use Gelf\Transport\UdpTransport;
use Hedii\LaravelGelfLogger\GelfLoggerFactory;
use Illuminate\Support\Facades\Log;
use LogicException;
use Monolog\Formatter\GelfMessageFormatter;
use Monolog\Handler\GelfHandler;
use Monolog\Level;
use Monolog\Logger;

class GelfLoggerTest extends TestCase
Expand All @@ -28,7 +30,7 @@ public function it_should_have_a_gelf_log_channel(): void
$handler = $logger->getHandlers()[0];

$this->assertInstanceOf(GelfHandler::class, $handler);
$this->assertSame(Logger::NOTICE, $handler->getLevel());
$this->assertSame(Level::Notice, $handler->getLevel());
$this->assertInstanceOf(GelfMessageFormatter::class, $handler->getFormatter());

$publisher = $this->getAttribute($logger->getHandlers()[0], 'publisher');
Expand All @@ -41,7 +43,7 @@ public function it_should_have_a_gelf_log_channel(): void
/** @test */
public function it_should_not_have_any_processor_if_the_config_does_not_have_processors(): void
{
$this->expectException(\LogicException::class);
$this->expectException(LogicException::class);
$this->expectExceptionMessage('You tried to pop from an empty processor stack.');

$logger = Log::channel('gelf');
Expand Down Expand Up @@ -214,7 +216,10 @@ public function it_should_set_path_to_default_path_if_path_is_null(): void
$publisher = $this->getAttribute($logger->getHandlers()[0], 'publisher');
$transport = $publisher->getTransports()[0];

$this->assertSame(HttpTransport::DEFAULT_PATH, $this->getAttribute($transport, 'path'));
$this->assertSame(
$this->getConstant(HttpTransport::class, 'DEFAULT_PATH'),
$this->getAttribute($transport, 'path')
);
}

/** @test */
Expand All @@ -231,7 +236,10 @@ public function it_should_set_path_to_default_path_if_path_is_not_provided(): vo
$publisher = $this->getAttribute($logger->getHandlers()[0], 'publisher');
$transport = $publisher->getTransports()[0];

$this->assertSame(HttpTransport::DEFAULT_PATH, $this->getAttribute($transport, 'path'));
$this->assertSame(
$this->getConstant(HttpTransport::class, 'DEFAULT_PATH'),
$this->getAttribute($transport, 'path')
);
}

/** @test */
Expand Down
48 changes: 27 additions & 21 deletions tests/GelfMessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

namespace Hedii\LaravelGelfLogger\Tests;

use DateTimeImmutable;
use Hedii\LaravelGelfLogger\GelfLoggerFactory;
use Illuminate\Support\Facades\Log;
use Monolog\Level;
use Monolog\LogRecord;

class GelfMessageTest extends TestCase
{
Expand All @@ -18,13 +21,14 @@ public function it_should_append_prefixes(): void
'extra_prefix' => 'extra_',
]);

$formattedMessage = Log::channel('gelf')->getHandlers()[0]->getFormatter()->format([
'datetime' => '1591097093.0',
'message' => 'test',
'level' => 100,
'extra' => ['ip' => '127.0.0.1', 'source' => 'tests'],
'context' => ['id' => '777', 'message' => 'custom'],
]);
$formattedMessage = Log::channel('gelf')->getHandlers()[0]->getFormatter()->format(new LogRecord(
datetime: new DateTimeImmutable(),
channel: 'gelf',
level: Level::Debug,
message: 'test',
context: ['id' => '777', 'message' => 'custom'],
extra: ['ip' => '127.0.0.1', 'source' => 'tests'],
));

$this->assertArrayHasKey('extra_ip', $formattedMessage->getAllAdditionals());
$this->assertArrayHasKey('extra_source', $formattedMessage->getAllAdditionals());
Expand All @@ -41,13 +45,14 @@ public function it_should_not_append_prefixes(): void
'via' => GelfLoggerFactory::class,
]);

$formattedMessage = Log::channel('gelf')->getHandlers()[0]->getFormatter()->format([
'datetime' => '1591097093.0',
'message' => 'test',
'level' => 100,
'extra' => ['ip' => '127.0.0.1'],
'context' => ['id' => '777'],
]);
$formattedMessage = Log::channel('gelf')->getHandlers()[0]->getFormatter()->format(new LogRecord(
datetime: new DateTimeImmutable(),
channel: 'gelf',
level: Level::Debug,
message: 'test',
context: ['id' => '777'],
extra: ['ip' => '127.0.0.1'],
));

$this->assertArrayHasKey('ip', $formattedMessage->getAllAdditionals());
$this->assertArrayHasKey('id', $formattedMessage->getAllAdditionals());
Expand All @@ -64,13 +69,14 @@ public function null_config_variables_should_not_add_prefixes(): void
'extra_prefix' => null,
]);

$formattedMessage = Log::channel('gelf')->getHandlers()[0]->getFormatter()->format([
'datetime' => '1591097093.0',
'message' => 'test',
'level' => 100,
'extra' => ['ip' => '127.0.0.1'],
'context' => ['id' => '777'],
]);
$formattedMessage = Log::channel('gelf')->getHandlers()[0]->getFormatter()->format(new LogRecord(
datetime: new DateTimeImmutable(),
channel: 'test_channel',
level: Level::Debug,
message: 'test',
context: ['id' => '777'],
extra: ['ip' => '127.0.0.1'],
));

$this->assertArrayHasKey('ip', $formattedMessage->getAllAdditionals());
$this->assertArrayHasKey('id', $formattedMessage->getAllAdditionals());
Expand Down

0 comments on commit 2a4f42d

Please sign in to comment.