stechstudio/laravel-metrics 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

stechstudio/laravel-metrics

Composer 安装命令:

composer require stechstudio/laravel-metrics

包简介

Easily track metrics from Laravel events, or on your own

README 文档

README

Latest Version on Packagist Total Downloads Software License

This package makes it incredibly easy to ship app metrics to backends such as PostHog, InfluxDB or CloudWatch.

There are two major components: a facade that lets you create metrics on your own, and an event listener to automatically send metrics for Laravel events.

Installation

You know the drill...

composer require stechstudio/laravel-metrics

Backend configuration

PostHog

  1. Install the PostHog PHP client: composer require posthog/posthog-php

  2. Add the following to your .env file:

METRICS_BACKEND=posthog
POSTHOG_API_KEY=...

InfluxDB v1.7 and under

  1. Install the InfluxDB PHP client: composer require influxdb/influxdb-php

  2. Add the following to your .env file:

METRICS_BACKEND=influxdb
IDB_USERNAME=...
IDB_PASSWORD=...
IDB_HOST=...
IDB_DATABASE=...
IDB_VERSION=1 # Default

# Only if you are not using the default 8086
IDB_TCP_PORT=...

# If you want to send metrics over UDP instead of TCP
IDB_UDP_PORT=...

InfluxDB V1.8 and above

  1. Install the InfluxDB PHP client: composer require influxdata/influxdb-client-php

  2. Add the following to your .env file:

  3. In order to use UDP with InfluxDB V1.8+ you must follow extra setup steps

Add the following to your .env file:

METRICS_BACKEND=influxdb
IDB_TOKEN=...
IDB_DATABASE=... # Use the name of your desired bucket for this value
IDB_HOST=...
IDB_ORG=...
IDB_VERSION=2

# Only if you are not using the default 8086
IDB_TCP_PORT=...

# If you want to send metrics over UDP instead of TCP
IDB_UDP_PORT=...

CloudWatch

  1. Install the AWS PHP SDK: composer require aws/aws-sdk-php.

  2. Add the following to your .env file:

METRICS_BACKEND=cloudwatch
CLOUDWATCH_NAMESPACE=...

AWS_DEFAULT_REGION=...
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...

Prometheus

  1. Install the Prometheus PHP client: composer require promphp/prometheus_client_php
  2. Configuring the backend to use Prometheus, makes sense only if you have an endpoint to expose them. Its purpose is only to format the registered metrics in a way that Prometheus can scrape them.
METRICS_BACKEND=prometheus

NullDriver (for development)

If you need to disable metrics just set the backend to null:

METRICS_BACKEND=null

This null driver will simply discard any metrics.

Sending an individual metric

You can create metric by using the facade like this:

Metrics::create('order_placed')
    ->setValue(1)
    ->setTags([
        'source' => 'email-campaign',
        'user' => 54
    ]);

The only required attribute is the name, everything else is optional.

Driver mapping

This is how we are mapping metric attributes in our backends.

Metric attribute PostHog InfluxDB CloudWatch Prometheus
name event measurement MetricName name
value properties[value] fields[value] Value value
unit ignored ignored Unit ignored
resolution ignored ignored StorageResolution ignored
tags ignored tags Dimensions keys -> labelNames
values -> labelValues
extra properties fields ignored ignored
timestamp ignored timestamp Timestamp ignored
description ignored ignored ignored help
namespace ignored ignored ignored namespace
type ignored ignored ignored used to register counter or gauge metric

See the CloudWatch docs and InfluxDB docs for more information on their respective data formats. Note we only do minimal validation, you are expected to know what data types and formats your backend supports for a given metric attribute.

Sending metrics from Laravel events

The main motivation for this library was to send metrics automatically when certain events occur in a Laravel application. So this is where things really get fun!

Let's say you have a simple Laravel event called OrderReceived:

class OrderReceived {
    protected $order;
    
    public function __construct($order)
    {
        $this->order = $order;
    }
}

The first step is to implement an interface:

use STS\Metrics\Contracts\ShouldReportMetric;

class OrderReceived implements ShouldReportMetric {

This will tell the global event listener to send a metric for this event.

There are two different ways you can then provide the metric details.

1. Use the ProvidesMetric trait

You can also include a trait that helps with building this metric:

use STS\Metrics\Contracts\ShouldReportMetric;
use STS\Metrics\Traits\ProvidesMetric;

class OrderReceived implements ShouldReportMetric {
    use ProvidesMetric;

In this case, the trait will build a metric called order_received (taken from the class name) with a value of 1.

Customizing event metric data

If you decide to use the trait, you likely will want to customize the event metric data.

You can provide metric data with class attributes:

class OrderReceived implements ShouldReportMetric {
    use ProvidesMetric;
    
    protected $metricName = "new_order";
    protected $metricTags = ["category" => "revenue"];
    ...

Or if some of your metric data is dynamic you can use getter methods:

public function getMetricValue()
{
    return $this->order->total;
}

You can provide any of our metric attributes using these class attributes or getter methods.

2. Create the metric yourself

Depending on how much detail you need to provide for your metric, it may be simpler to just build it yourself. In this case you can ditch the trait and simply provide a public createMetric function that returns a new Metric instance:

use STS\Metrics\Contracts\ShouldReportMetric;
use STS\Metrics\Metric;

class OrderReceived implements ShouldReportMetric {
    protected $order;
    
    public function __construct($order)
    {
        $this->order = $order;
    }
    
    public function createMetric()
    {
        return (new Metric('order_received'))
            ->setValue(...)
            ->setTags([...])
            ->setTimestamp(...)
            ->setResolutions(...);
    }
}

Default tags and extra data

You can set default tags and extra data on the driver that will be merged into every metric:

Metrics::setTags(['environment' => 'production']);
Metrics::setExtra(['server' => 'web-01']);

Dynamic extra data with closures

If you need extra data that is evaluated at the time each metric is dispatched (rather than when it's initially set), you can pass a closure:

Metrics::setExtra(fn() => [
    'memory' => memory_get_usage(),
    'cpu' => sys_getloadavg()[0],
]);

The closure will be called fresh each time a metric is formatted. This also works on individual metrics:

(new Metric('my_metric'))
    ->setExtra(fn() => ['memory' => memory_get_usage()])
    ->add();

User ID resolution

Drivers automatically resolve the current user ID via getUserId():

  1. If a user is authenticated: auth()->id()
  2. Otherwise: getAnonymousId(), which returns a UUID stored in the session (stable across requests), or a static UUID for non-session contexts (CLI, queues)

This is used by the PostHog driver as the distinctId, and is available to any driver via $driver->getUserId().

Custom user ID resolver

You can override the default resolution by providing your own closure. The driver instance is passed to your closure, so you can fall back to the built-in anonymous ID if needed:

Metrics::resolveUserIdUsing(function($driver) {
    return auth()->check()
        ? 'custom-prefix:' . auth()->id()
        : $driver->getAnonymousId();
});

This will apply to all drivers. You can also set it on a specific driver:

Metrics::driver('posthog')->resolveUserIdUsing(fn() => $team->id);

stechstudio/laravel-metrics 适用场景与选型建议

stechstudio/laravel-metrics 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 225.81k 次下载、GitHub Stars 达 50, 最近一次更新时间为 2017 年 10 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 stechstudio/laravel-metrics 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 225.81k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 50
  • 点击次数: 24
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 50
  • Watchers: 3
  • Forks: 9
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-10-23