PHPackages                             hamidrezaniazi/pecs - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. hamidrezaniazi/pecs

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

hamidrezaniazi/pecs
===================

PHP ECS (Elastic Common Schema): Simplify logging with the power of elastic common schema.

2.0.0(1y ago)3325.5k↓10.6%31MITPHPPHP ^8.1CI passing

Since May 28Pushed 1y ago4 watchersCompare

[ Source](https://github.com/hamidrezaniazi/pecs)[ Packagist](https://packagist.org/packages/hamidrezaniazi/pecs)[ Docs](https://github.com/hamidrezaniazi/pecs)[ RSS](/packages/hamidrezaniazi-pecs/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (7)Versions (7)Used By (1)

PECS
====

[](#pecs)

PHP ECS (Elastic Common Schema)

[![Latest Version on Packagist](https://camo.githubusercontent.com/01d92a2d62b4c906c580c412d6ee932d0b6bb8c13476bc3b1f63c5f105a950f8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f68616d696472657a616e69617a692f706563732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hamidrezaniazi/pecs)[![License](https://camo.githubusercontent.com/f7fc5dc0f3ad66e8bf3154512d4b08dc28fd356204bb108070199b3b4f373bb5/68747470733a2f2f706f7365722e707567782e6f72672f68616d696472657a616e69617a692f706563732f6c6963656e7365)](https://packagist.org/packages/hamidrezaniazi/pecs)[![Total Downloads](https://camo.githubusercontent.com/b4595c816c6a8c1290966a90cf70eaf13a2d62e6ac8c0aaf7a804d6287b9ab02/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f68616d696472657a616e69617a692f706563732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hamidrezaniazi/pecs)

PECS is a PHP package that facilitates the usage of [ECS (Elastic Common Schema)](https://www.elastic.co/guide/en/ecs/current/ecs-reference.html) within PHP applications. ECS is a specification that helps structure and standardize log events.

PECS offers a practical approach for integrating ECS into PHP applications. By utilizing type-hinted classes, you can enhance your data layers with ECS fields. PECS simplifies the transformation of these data layers into the standard ECS schema.

1. [Installation](#installation)
2. [Integrations](#integrations)
    1. [Monolog](#monolog)
    2. [Symfony](#symfony)
    3. [Laravel](#laravel)
3. [Usage](#usage)
    1. [Helpers](#helpers)
    2. [Multiple Fields](#multiple-fields)
    3. [Custom Fields](#custom-fields)
        1. [Wrapper](#wrapper)
        2. [Empty Values](#empty-values)
    4. [Custom Formatter](#custom-formatter)
    5. [Collection](#collection)
4. [Testing](#testing)
5. [Security](#security)
6. [License](#license)
7. [Changelog](#changelog)
8. [Contributing](#contributing)

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require hamidrezaniazi/pecs
```

Integrations
------------

[](#integrations)

### Monolog

[](#monolog)

PECS can be used with the popular PHP logging library, [Monolog](https://github.com/Seldaek/monolog) to apply the formatter to handlers.

```
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Hamidrezaniazi\Pecs\Monolog\EcsFormatter;
use Hamidrezaniazi\Pecs\Fields\Event;

$log = new Logger('logger name');
$handler = new StreamHandler('ecs.logs');

$log->pushHandler($handler->setFormatter(new EcsFormatter()));

$log->info('message', [
    new Event(action: 'test event'),
]);
```

The `EcsFormatter` ensures that the default records generated by Monolog are correctly mapped to the corresponding ECS fields. Additionally, it takes care of rendering the remaining fields in the context array to align with the ECS schema. Here is the output of the above example:

```
[
    '@timestamp' => '2023-05-27T00:13:16Z',
    'message' => 'message',
    'log' => [
        'level' => 'INFO',
        'logger' => 'logger name',
    ],
    'event' => [
        'action' => 'test event',
    ],
]
```

### Symfony

[](#symfony)

In Symfony applications, you can apply the `EcsFormatter` to a logging channel. First, you need to define it as a service in `config/services.yaml`:

```
services:
    ecs:
        class: Hamidrezaniazi\Pecs\Monolog\EcsFormatter
```

Then define a custom channel in `config/packages/monolog.yaml`:

```
monolog:
    channels:
        - ecs
    handlers:
        ecs:
            formatter: ecs
            type: stream
            path: '%kernel.logs_dir%/ecs.log'
            channels: [ "ecs" ]
```

Now, you can use the `ecs` channel in your Symfony application by autowring the logger channel:

```
public function __construct(LoggerInterface $ecsLogger)
{
    $ecsLogger->info('sample message', [
        new Event(kind: EventKind::METRIC),
    ]);
}
```

> See [Symfony's documentation](https://symfony.com/doc/current/logging/channels_handlers.html#how-to-autowire-logger-channels) for more information.

### Laravel

[](#laravel)

In Laravel applications, you can apply the `EcsFormatter` to a logging driver. First, you need to create a class that implements the `__invoke` method like bellow:

```
use Illuminate\Log\Logger;
use Monolog\Handler\FormattableHandlerInterface;
use Hamidrezaniazi\Pecs\Monolog\EcsFormatter;

class LaravelEcsFormatter
{
    public function __invoke(Logger $logger): void
    {
        foreach ($logger->getHandlers() as $handler) {
            /** @var FormattableHandlerInterface $handler */
            $handler->setFormatter(app(EcsFormatter::class));
        }
    }
}
```

Then to apply this formatter to the logging driver, you need to add the `tap` key to the desired logging configuration in `config/logging.php`:

```
'ecs' => [
    'driver' => 'single',
    'tap' => [LaravelEcsFormatter::class],
    'path' => storage_path('logs/ecs.log'),
    'level' => 'debug',
],
```

> See [Laravel's documentation](https://laravel.com/docs/master/logging#customizing-monolog-for-channels) for more information about this method.

Now, you can use the `ecs` driver in your Laravel application's logging configuration to apply the ECS formatter to the logs.

```
Log::channel('ecs')->info('sample message', [
    new Event(kind: EventKind::METRIC),
]);
```

Since Laravel utilizes Monolog as its underlying logging system, the same behavior is applicable here regarding the automatic configuration of the `@timestamp`, `message`, `level`, and `logger` fields.

Usage
-----

[](#usage)

> It's important to note that empty values such as `null`, `[]`, etc., in the data layers are eliminated automatically. You don't need to handle them explicitly as strings like `N/A`. However, these values `0`, `0.0`, `'0'`, `'0.0'`, `false`, `'false'` are whitelisted and will appear in the logs.

### Helpers

[](#helpers)

The syntax can get a little bit verbose when you want to log with several fields. To make it more concise, you can implement helper classes:

```
use Hamidrezaniazi\Pecs\Fields\Error;
use Hamidrezaniazi\Pecs\Fields\Log;

class ThrowableHelper
{
    public static function from(Throwable $throwable): array
    {
        return [
            new Error(
                code: $throwable->getCode(),
                message: $throwable->getMessage(),
                stackTrace: $throwable->getTraceAsString(),
                type: get_class($throwable),
            ),
            new Log(
                originFileLine: $throwable->getLine(),
                originFileName: $throwable->getFile(),
            )
        ];
    }
}
```

Then the usage would be shortened to:

```
try {
    // ...
} catch (Throwable $throwable) {
    Log::error('helpers example', ThrowableHelper::from($throwable));
}
```

### Multiple Fields

[](#multiple-fields)

It is completely possible to have multiple fields of the same type. In case of a conflict, the most recent properties will take priority.

```
use Hamidrezaniazi\Pecs\EcsFieldsCollection;
use Hamidrezaniazi\Pecs\Fields\Base;
use Hamidrezaniazi\Pecs\Properties\ValueList;

(new EcsFieldsCollection([
    new Base(message: 'Hello World'),
    new Base(message: 'test', tags: (new ValueList())->push('staging')),
]))->render()->toArray();
```

```
[
    'message' => 'test',
    'tags' => [
        'staging',
    ],
]
```

You can find the available classes for defining ECS fields in the [this](https://github.com/hamidrezaniazi/pecs/tree/master/src/Fields) directory.

### Custom Fields

[](#custom-fields)

You can also create your own custom fields by extending the `AbstractEcsField` class.

```
use Hamidrezaniazi\Pecs\Fields\AbstractEcsField;

class FooField extends AbstractEcsField
{
    public function __construct(
        private string $input
    ) {
        parent::__construct();
    }

    protected function key(): ?string
    {
        return 'Foo';
    }

    protected function custom(): Collection
    {
        return collect([
            'Input' => $this->input
        ]);
    }
}
```

> Check the [ECS custom fields documentation](https://www.elastic.co/guide/en/ecs/master/ecs-custom-fields-in-ecs.html) for naming conventions and use cases. It is important to note that custom field key and property names must be in PascalCase not to conflict with the ECS fields.

#### Wrapper

[](#wrapper)

You may need to combine your custom fields with the existed ECS field classes. It's feasible by overwriting the `wrapper` in your class:

```
use Hamidrezaniazi\Pecs\Fields\AbstractEcsField;
use Hamidrezaniazi\Pecs\Fields\Event;
use Hamidrezaniazi\Pecs\Properties\EventKind;

class BarField extends AbstractEcsField
{
    protected function key(): ?string
    {
        return 'Bar';
    }

    protected function custom(): Collection
    {
        return collect([
            'Bleep' => 'bloop'
        ]);
    }

    public function wrapper(): EcsFieldsCollection
    {
        return parent::wrapper()->push(new Event(kind: EventKind::METRIC));
    }
```

All the fields in the wrapper will be rendered at the same level as the custom field. In the given example, the rendered array will be:

```
[
    'Bar' => [
        'Bleep' => 'bloop',
    ],
    'event' => [
        'kind' => 'metric',
    ],
]
```

#### Empty Values

[](#empty-values)

It's also possible to customize the empty value behavior by overriding the whitelisted array:

```
class FooFields extends AbstractEcsField
{
    protected array $validEmpty = [0, 0.0];
```

Now only `0` and `0.0` are whitelisted and will appear in the logs. The rest of the empty values such as `null`, `[]`, `false`, `'0'`, etc., will be eliminated.

### Custom Formatter

[](#custom-formatter)

The default formatter is the `EcsFormatter` class as mentioned in the [integration](#integration) section. However, you can load more default fields by overriding the `prepare` method:

```
