承接 hamidrezaniazi/pecs 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

hamidrezaniazi/pecs

Composer 安装命令:

composer require hamidrezaniazi/pecs

包简介

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

README 文档

README

PHP ECS (Elastic Common Schema)

Latest Version on Packagist License Total Downloads

PECS is a PHP package that facilitates the usage of ECS (Elastic Common Schema) 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
  2. Integrations
    1. Monolog
    2. Symfony
    3. Laravel
  3. Usage
    1. Helpers
    2. Multiple Fields
    3. Custom Fields
      1. Wrapper
      2. Empty Values
    4. Custom Formatter
    5. Collection
  4. Testing
  5. Security
  6. License
  7. Changelog
  8. Contributing

Installation

You can install the package via composer:

composer require hamidrezaniazi/pecs

Integrations

Monolog

PECS can be used with the popular PHP logging library, 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

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 for more information.

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 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

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

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

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 directory.

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 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

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

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

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

<?php

use Hamidrezaniazi\Pecs\Fields\Ecs;
use Hamidrezaniazi\Pecs\Monolog\EcsFormatter;

class CustomEcsFormatter extends EcsFormatter
{
    protected function prepare(array $record): EcsFieldsCollection
    {
        return parent::prepare($record)->push(new Ecs(version: '1.0.0'));
    }
}

By registering the above formatter, the rendered array will contain the ecs.version in addition to the default fields.

Collection

Here's the usage example of the EcsFieldsCollection to render an array of ECS fields:

use Hamidrezaniazi\Pecs\EcsFieldsCollection;
use Hamidrezaniazi\Pecs\Fields\Base;
use Hamidrezaniazi\Pecs\Fields\Log;

(new EcsFieldsCollection([
    new Base(message: 'Hello World'),
    new Log(level: 'info'),
]))->render()->toArray();

The above code will output:

[
    'message' => 'Hello World',
    'log' => [
        'level' => 'info',
    ],
]

The EcsFieldsCollection is adaptable and can be used with various logging drivers, not just limited to Monolog. Practical use cases for Monolog are mentioned in the integrations section.

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

hamidrezaniazi/pecs 适用场景与选型建议

hamidrezaniazi/pecs 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 31.05k 次下载、GitHub Stars 达 33, 最近一次更新时间为 2023 年 05 月 27 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「log」 「logging」 「elastic」 「ECS」 「filebeat」 「hamidrezaniazi」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 hamidrezaniazi/pecs 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 hamidrezaniazi/pecs 我们能提供哪些服务?
定制开发 / 二次开发

基于 hamidrezaniazi/pecs 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 31.05k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 33
  • 点击次数: 17
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 33
  • Watchers: 4
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-05-27