Skip to content

Commit

Permalink
Merge pull request #3 from avto-dev/add-logstash-udp
Browse files Browse the repository at this point in the history
Add logstash udp
  • Loading branch information
tarampampam authored Apr 11, 2019
2 parents 816c6c7 + 2a2d832 commit 32b77db
Show file tree
Hide file tree
Showing 17 changed files with 602 additions and 23 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ before_install:
install:
- if [[ $setup = 'basic' ]]; then travis_retry composer update --prefer-dist --no-interaction --no-suggest; fi
- if [[ $setup = 'stable' ]]; then travis_retry composer update --prefer-dist --no-interaction --no-suggest --prefer-stable; fi
- if [[ $setup = 'lowest' ]]; then travis_retry composer update --prefer-dist --no-interaction --no-suggest --prefer-stable --prefer-lowest; fi
- if [[ $setup = 'lowest' ]]; then travis_retry composer update --prefer-dist --no-interaction --no-suggest --prefer-lowest; fi

script:
- composer phpstan
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog][keepachangelog] and this project adheres to [Semantic Versioning][semver].

## v1.3.0

### Added

- Sending logstash logs using UDP protocol (`DefaultUdpLogstashLogger` and `EventsUdpLogstashLogger` loggers)

## v1.2.0

### Added
Expand Down
44 changes: 41 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
Require this package with composer using the following command (`laravel/framework` version 5.6 and above is required):

```shell
$ composer require avto-dev/events-log-laravel "^1.2"
$ composer require avto-dev/events-log-laravel "^1.3"
```

> Installed `composer` is required ([how to install composer][getcomposer]).
Expand Down Expand Up @@ -88,6 +88,42 @@ return [
];
```

Для отправки логов в формате `Logstash` по UDP протоколу:

```php
<?php

return [

'default' => env('LOG_CHANNEL', 'app-logstash-udp'),

'events_channel' => env('EVENTS_LOG_CHANNEL', 'events-logstash-udp'),

// ...

'channels' => [

// ...

'app-logstash-udp' => [
'driver' => 'custom',
'via' => AvtoDev\EventsLogLaravel\Logging\DefaultUdpLogstashLogger::class,
'host' => env('LOGSTASH_UDP_HOST', 'logstash'),
'port' => (int) env('LOGSTASH_UDP_PORT', 4560),
'level' => 'debug',
],

'events-logstash-udp' => [
'driver' => 'custom',
'via' => AvtoDev\EventsLogLaravel\Logging\EventsUdpLogstashLogger::class,
'host' => env('LOGSTASH_UDP_HOST', 'logstash'),
'port' => (int) env('LOGSTASH_UDP_PORT', 4560),
'level' => 'debug',
],
],
];
```

Более подробно о настройке логгирования вы можете прочитать по [этой ссылке][laravel_logging].


Expand Down Expand Up @@ -184,8 +220,10 @@ class YourEvent implements \AvtoDev\EventsLogLaravel\Contracts\ShouldBeLoggedCon

Класс логгера | Назначение
---------------- | ----------
`DefaultLogstashLogger` | Пишет лог-записи в формате `logstash`, не видоизменяя тело записи (поле `context` не изменяется)
`EventsLogstashLogger` | Пишет лог-записи в формате `logstash`, но данные связанные с событиями помещаются в секцию `event`
`DefaultLogstashLogger` | Пишет лог-записи в формате `logstash` в файл, не видоизменяя тело записи (поле `context` не изменяется)
`EventsLogstashLogger` | Пишет лог-записи в формате `logstash` в файл, но данные связанные с событиями помещаются в секцию `event`
`DefaultUdpLogstashLogger` | Отправляет лог-записи в формате `logstash` по UDP протоколу, не видоизменяя тело записи (поле `context` не изменяется)
`EventsUdpLogstashLogger` | Пишет лог-записи в формате `logstash` по UDP протоколу, но данные связанные с событиями помещаются в секцию `event`

> Более подробно о них смотрите исходный код
Expand Down
4 changes: 4 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"laravel/framework": ">=5.6.0 <5.8.0"
},
"require-dev": {
"ext-sockets": "*",
"avto-dev/dev-tools": "^1.7",
"laravel/laravel": ">=5.6.0 <5.8.0",
"phpunit/phpunit": "~7.0",
Expand Down Expand Up @@ -50,6 +51,9 @@
]
}
},
"suggest": {
"ext-sockets": "For a sending data using TCP\\UDP sockets"
},
"support": {
"issues": "https://github.com/avto-dev/events-log-laravel/issues",
"source": "https://github.com/avto-dev/events-log-laravel"
Expand Down
File renamed without changes.
8 changes: 5 additions & 3 deletions src/Logging/DefaultLogstashLogger.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

declare(strict_types=1);
declare(strict_types = 1);

namespace AvtoDev\EventsLogLaravel\Logging;

Expand All @@ -13,6 +13,8 @@

class DefaultLogstashLogger implements LoggerContract
{
use Traits\AppNameTrait;

/**
* {@inheritdoc}
*
Expand All @@ -21,7 +23,7 @@ class DefaultLogstashLogger implements LoggerContract
public function __invoke(array $config): Logger
{
$formatter = new DefaultLogstashFormatter(
$config['formatter']['app_name'] ?? resolve('config')->get('app.name'),
$config['formatter']['app_name'] ?? $this->getAppName() ?? 'app',
$config['formatter']['system_name'] ?? null,
$config['formatter']['extra_prefix'] ?? false,
$config['formatter']['context_prefix'] ?? null,
Expand All @@ -30,7 +32,7 @@ public function __invoke(array $config): Logger

$handler = new StreamHandler(
$config['path'] ?? storage_path('logs/logstash/laravel.log'),
$config['level'] ?? 'debug',
Logger::toMonologLevel($config['level'] ?? 'debug'),
$config['bubble'] ?? true,
$config['permission'] ?? null,
$config['locking'] ?? false
Expand Down
48 changes: 48 additions & 0 deletions src/Logging/DefaultUdpLogstashLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types = 1);

namespace AvtoDev\EventsLogLaravel\Logging;

use Exception;
use Monolog\Logger;
use InvalidArgumentException;
use Monolog\Formatter\LogstashFormatter;
use AvtoDev\EventsLogLaravel\Contracts\LoggerContract;
use AvtoDev\EventsLogLaravel\Logging\Formatters\DefaultLogstashFormatter;

class DefaultUdpLogstashLogger implements LoggerContract
{
use Traits\AppNameTrait;

/**
* {@inheritdoc}
*
* @throws Exception
*/
public function __invoke(array $config): Logger
{
if (! isset($config['host'], $config['port'])) {
throw new InvalidArgumentException('[host] and [port] values are required for this logger');
}

$formatter = new DefaultLogstashFormatter(
$config['formatter']['app_name'] ?? $this->getAppName() ?? 'app',
$config['formatter']['system_name'] ?? null,
$config['formatter']['extra_prefix'] ?? false,
$config['formatter']['context_prefix'] ?? null,
$config['formatter']['version'] ?? LogstashFormatter::V1
);

$handler = new Handlers\UdpHandler(
(string) $config['host'],
(int) $config['port'],
Logger::toMonologLevel($config['level'] ?? Logger::DEBUG), // The minimum logging level
(bool) ($config['bubble'] ?? true), // Whether the messages that are handled can bubble up the stack or not
(bool) ($config['silent'] ?? true)
);

return (new Logger($config['name'] ?? app()->environment()))
->pushHandler($handler->setFormatter($formatter));
}
}
8 changes: 5 additions & 3 deletions src/Logging/EventsLogstashLogger.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

declare(strict_types=1);
declare(strict_types = 1);

namespace AvtoDev\EventsLogLaravel\Logging;

Expand All @@ -13,6 +13,8 @@

class EventsLogstashLogger implements LoggerContract
{
use Traits\AppNameTrait;

/**
* {@inheritdoc}
*
Expand All @@ -21,7 +23,7 @@ class EventsLogstashLogger implements LoggerContract
public function __invoke(array $config): Logger
{
$formatter = new EventsLogstashFormatter(
$config['formatter']['app_name'] ?? resolve('config')->get('app.name'),
$config['formatter']['app_name'] ?? $this->getAppName() ?? 'app',
$config['formatter']['system_name'] ?? null,
$config['formatter']['extra_prefix'] ?? false,
$config['formatter']['context_prefix'] ?? null,
Expand All @@ -30,7 +32,7 @@ public function __invoke(array $config): Logger

$handler = new StreamHandler(
$config['path'] ?? storage_path('logs/logstash/laravel-events.log'),
$config['level'] ?? 'debug',
Logger::toMonologLevel($config['level'] ?? 'debug'),
$config['bubble'] ?? true,
$config['permission'] ?? null,
$config['locking'] ?? false
Expand Down
48 changes: 48 additions & 0 deletions src/Logging/EventsUdpLogstashLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types = 1);

namespace AvtoDev\EventsLogLaravel\Logging;

use Exception;
use Monolog\Logger;
use InvalidArgumentException;
use Monolog\Formatter\LogstashFormatter;
use AvtoDev\EventsLogLaravel\Contracts\LoggerContract;
use AvtoDev\EventsLogLaravel\Logging\Formatters\EventsLogstashFormatter;

class EventsUdpLogstashLogger implements LoggerContract
{
use Traits\AppNameTrait;

/**
* {@inheritdoc}
*
* @throws Exception
*/
public function __invoke(array $config): Logger
{
if (! isset($config['host'], $config['port'])) {
throw new InvalidArgumentException('[host] and [port] values are required for this logger');
}

$formatter = new EventsLogstashFormatter(
$config['formatter']['app_name'] ?? $this->getAppName() ?? 'app',
$config['formatter']['system_name'] ?? null,
$config['formatter']['extra_prefix'] ?? false,
$config['formatter']['context_prefix'] ?? null,
$config['formatter']['version'] ?? LogstashFormatter::V1
);

$handler = new Handlers\UdpHandler(
(string) $config['host'],
(int) $config['port'],
Logger::toMonologLevel($config['level'] ?? Logger::DEBUG), // The minimum logging level
(bool) ($config['bubble'] ?? true), // Whether the messages that are handled can bubble up the stack or not
(bool) ($config['silent'] ?? true)
);

return (new Logger($config['name'] ?? app()->environment()))
->pushHandler($handler->setFormatter($formatter));
}
}
22 changes: 11 additions & 11 deletions src/Logging/Formatters/AbstractLogstashFormatter.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

declare(strict_types=1);
declare(strict_types = 1);

namespace AvtoDev\EventsLogLaravel\Logging\Formatters;

Expand All @@ -21,24 +21,24 @@ protected function formatV0(array $record)
}

/**
* Format record for 'v1' format.
* Modify parent formatted message.
*
* @param array $parent_message
* @param array $record
*
* @return array Message
* @return array Message as an array
*/
protected function formatV1(array $record)
{
return $this->modifyParentMessage(parent::formatV1($record), $record);
}
abstract protected function modifyParentMessage(array $parent_message, array $record): array;

/**
* Modify parent formatted message.
* Format record for 'v1' format.
*
* @param array $parent_message
* @param array $record
*
* @return array Message as an array
* @return array Message
*/
abstract protected function modifyParentMessage(array $parent_message, array $record): array;
protected function formatV1(array $record)
{
return $this->modifyParentMessage(parent::formatV1($record), $record);
}
}
2 changes: 1 addition & 1 deletion src/Logging/Formatters/DefaultLogstashFormatter.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

declare(strict_types=1);
declare(strict_types = 1);

namespace AvtoDev\EventsLogLaravel\Logging\Formatters;

Expand Down
2 changes: 1 addition & 1 deletion src/Logging/Formatters/EventsLogstashFormatter.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

declare(strict_types=1);
declare(strict_types = 1);

namespace AvtoDev\EventsLogLaravel\Logging\Formatters;

Expand Down
Loading

0 comments on commit 32b77db

Please sign in to comment.