moesif/moesif-laravel

Moesif 集成/Laravel 数据摄取中间件

2.0.6 2021-01-19 21:47 UTC

README

Built For Latest Version Total Downloads Software License Source Code

GitHub 上的源代码

用于 PHP Laravel (大于 5.1) 的中间件,可自动记录 API 调用并将其发送到 Moesif 以进行 API 分析和日志分析

Laravel 4.2

为 Laravel 4.2 提供 Moesif SDK。感谢 jonnypickett 创建此 SDK。

如何安装

通过 Composer

$ composer require moesif/moesif-laravel

或将 'moesif/moesif-laravel' 添加到您的 composer.json 文件中。

如何使用

添加服务提供者

// In config/app.php

'providers' => [
  /*
   * Application Service Providers...
   */
    Moesif\Middleware\MoesifLaravelServiceProvider::class,
];

添加到中间件

如果网站根目录是您的 API,则添加到根级别

// In App/Http/Kernel.php

protected $middleware = [
  /*
   * The application's global HTTP middleware stack.
   *
   * These middleware are run during every request to your application.
   */
   \Moesif\Middleware\MoesifLaravel::class,
];

如果您只想为特定路由组的 API 添加跟踪,则添加到您的路由组,但请确保从上面的全局中间件堆栈中删除。

// In App/Http/Kernel.php

protected $middlewareGroups = [
  /**
   * The application's API route middleware group.
   */
   'api' => [
        //
        \Moesif\Middleware\MoesifLaravel::class,
    ],
];

要跟踪特定路由,请使用特定路由的中间件设置。

发布包配置文件

$ php artisan vendor:publish --provider="Moesif\Middleware\MoesifLaravelServiceProvider"

配置设置

编辑 config/moesif.php 文件。

// In config/moesif.php

return [
    //
    'applicationId' => 'Your Moesif Application Id',
    'logBody' => true,
];

您的 Moesif 应用程序 ID 可在 Moesif 门户 中找到。注册 Moesif 账户后,您的 Moesif 应用程序 ID 将在入门步骤中显示。

您可以通过登录到 Moesif 门户,点击右上角菜单,然后点击 安装 来随时找到您的 Moesif 应用程序 ID。

有关其他配置选项,请参见以下内容。

配置选项

为了支持 Laravel 配置缓存,一些配置选项已移动到单独的配置类中(v2 版本)。请参阅 迁移指南 v1.x.x 到 v2.x.x

您可以在 config/moesif.php 文件中定义 Moesif 配置选项。

applicationId

类型:String 必需的,一个标识您应用程序的字符串。

disableForking

类型:Boolean 可选的,如果为 true,则将禁用分支。为了最佳性能,SDK 默认会通过分支进程来发送事件。但是,这要求您的 PHP 环境未通过 disable_functions 禁用 exec

debug

类型:Boolean 可选的,如果为 true,则将使用 Illuminate\Support\Facades\Log 打印调试信息。

logBody

类型:Boolean 可选的,默认为 true,设置为 false 以从 Moesif 中删除请求和响应体的日志记录。

apiVersion

类型:String 可选的,一个指定 API 版本的字符串,例如 1.0.1,允许更容易的筛选。

configClass

类型:String 可选的,一个包含额外函数的类的完整路径(包括命名空间)。该类可以位于任何命名空间中,只要提供了完整的命名空间即可。

示例

return [
    ...
    'configClass' => 'MyApp\\MyConfigs\\CustomMoesifConfig',
    ...
];

配置类

由于配置钩子和函数不能放在 config/moesif.php 文件中,因此这些位于您创建的 PHP 类中。使用 configClass 选项设置此类的路径。您可以定义以下任何钩子

identifyUserId

类型: ($request, $response) => String 可选,一个接收 $request 和 $response 并返回 userId 字符串的函数。Moesif 会自动通过 $request->user()['id'] 获取最终用户 ID,如果您使用非标准方式将用户注入到 $request 中或想要覆盖 userId,可以使用 identifyUserId 来实现。

identifyCompanyId

类型: ($request, $response) => String 可选,一个接收 $request 和 $response 并返回 companyId 字符串的函数。

identifySessionId

类型: ($request, $response) => String 可选,一个接收 $request 和 $response 并返回 sessionId 字符串的函数。Moesif 会自动通过处理您的数据来会话化,但如果您对结果不满意,可以通过 identifySessionId 来覆盖。

getMetadata

类型: ($request, $response) => 关联数组 可选,一个接收 $request 和 $response 并返回 $metdata 的函数,$metdata 是 JSON 的关联数组表示形式。

maskRequestHeaders

类型: $headers => $headers 可选,一个接收 $headers(关联数组)并返回移除/遮蔽敏感头部的关联数组的函数。

maskRequestBody

类型: $body => $body 可选,一个接收 $body(JSON 的关联数组表示形式)并返回移除任何信息的关联数组的函数。

maskResponseHeaders

类型: $headers => $headers 可选,与上面相同,但用于响应。

maskResponseBody

类型: $body => $body 可选,与上面相同,但用于响应。

skip

类型: ($request, $response) => String 可选,一个接收 $request 和 $response 并返回 true 如果此 API 调用不应发送到 Moesif 的函数。

示例配置类

namespace MyApp\MyConfigs;

class CustomMoesifConfig
{
    public function maskRequestHeaders($headers) {
      $headers['header5'] = '';
      return $headers;
    }

    public function maskRequestBody($body) {
      return $body;
    }

    public function maskResponseHeaders($headers) {
      $headers['header2'] = 'XXXXXX';
      return $headers;
    }

    public function maskResponseBody($body) {
      return $body;
    }

    public function identifyUserId($request, $response) {
      if (is_null($request->user())) {
        return null;
      } else {
        $user = $request->user();
        return $user['id'];
      }
    }

    public function identifyCompanyId($request, $response) {
      return "67890";
    }

    public function identifySessionId($request, $response) {
      if ($request->hasSession()) {
        return $request->session()->getId();
      } else {
        return null;
      }
    }

    public function getMetadata($request, $response) {
      return array("foo"=>"a", "boo"=>"b");
    }

    public function skip($request, $response) {
      $myurl = $request->fullUrl();
      if (strpos($myurl, '/health') !== false) {
        return true;
      }
      return false;
    }
}

更新单个用户

在 Moesif 中创建或更新用户配置文件。元数据字段可以是任何客户人口统计信息或其他您想要存储的信息。只需 user_id 字段是必需的。

use Moesif\Middleware\MoesifLaravel;

// Only userId is required.
// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#users for campaign schema
// metadata can be any custom object
$user = array(
    "user_id" => "12345",
    "company_id" => "67890", // If set, associate user with a company object
    "campaign" => array(
        "utm_source" => "google",
        "utm_medium" => "cpc",
        "utm_campaign" => "adwords",
        "utm_term" => "api+tooling",
        "utm_content" => "landing"
    ),
    "metadata" => array(
        "email" => "john@acmeinc.com",
        "first_name" => "John",
        "last_name" => "Doe",
        "title" => "Software Engineer",
        "sales_info" => array(
            "stage" => "Customer",
            "lifetime_value" => 24000,
            "account_owner" => "mary@contoso.com"
        )
    )
);

$middleware = new MoesifLaravel();
$middleware->updateUser($user);

metadata 字段可以是您想要在用户上设置的任何自定义数据。需要 user_id 字段。

批量更新用户

类似于 updateUser,但用于在单个批处理中更新用户列表。只需 user_id 字段是必需的。

use Moesif\Middleware\MoesifLaravel;

$userA = array(
    "user_id" => "12345",
    "company_id" => "67890", // If set, associate user with a company object
    "campaign" => array(
        "utm_source" => "google",
        "utm_medium" => "cpc",
        "utm_campaign" => "adwords",
        "utm_term" => "api+tooling",
        "utm_content" => "landing"
    ),
    "metadata" => array(
        "email" => "john@acmeinc.com",
        "first_name" => "John",
        "last_name" => "Doe",
        "title" => "Software Engineer",
        "sales_info" => array(
            "stage" => "Customer",
            "lifetime_value" => 24000,
            "account_owner" => "mary@contoso.com"
        )
    )
);

$userB = array(
    "user_id" => "12345",
    "company_id" => "67890", // If set, associate user with a company object
    "campaign" => array(
        "utm_source" => "google",
        "utm_medium" => "cpc",
        "utm_campaign" => "adwords",
        "utm_term" => "api+tooling",
        "utm_content" => "landing"
    ),
    "metadata" => array(
        "email" => "john@acmeinc.com",
        "first_name" => "John",
        "last_name" => "Doe",
        "title" => "Software Engineer",
        "sales_info" => array(
            "stage" => "Customer",
            "lifetime_value" => 24000,
            "account_owner" => "mary@contoso.com"
        )
    )
);

$users = array($userA);

$middleware = new MoesifLaravel();
$middleware->updateUsersBatch($users);

metadata 字段可以是您想要在用户上设置的任何自定义数据。需要 user_id 字段。

更新单个公司

在 Moesif 中创建或更新公司配置文件。元数据字段可以是任何公司人口统计信息或其他您想要存储的信息。只需 company_id 字段是必需的。

use Moesif\Middleware\MoesifLaravel;

// Only companyId is required.
// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#update-a-company for campaign schema
// metadata can be any custom object
$company = array(
    "company_id" => "67890",
    "company_domain" => "acmeinc.com", // If domain is set, Moesif will enrich your profiles with publicly available info
    "campaign" => array(
        "utm_source" => "google",
        "utm_medium" => "cpc",
        "utm_campaign" => "adwords",
        "utm_term" => "api+tooling",
        "utm_content" => "landing"
    ),
    "metadata" => array(
        "org_name" => "Acme, Inc",
        "plan_name" => "Free",
        "deal_stage" => "Lead",
        "mrr" => 24000,
        "demographics" => array(
            "alexa_ranking" => 500000,
            "employee_count" => 47
        )
    )
);

$middleware = new MoesifLaravel();
$middleware->updateCompany($company);

metadata 字段可以是您想要在公司上设置的任何自定义数据。需要 company_id 字段。

批量更新公司

类似于 update_company,但用于在单个批处理中更新公司列表。只需 company_id 字段是必需的。

use Moesif\Middleware\MoesifLaravel;

$companyA = array(
    "company_id" => "67890",
    "company_domain" => "acmeinc.com", // If domain is set, Moesif will enrich your profiles with publicly available info
    "campaign" => array(
        "utm_source" => "google",
        "utm_medium" => "cpc",
        "utm_campaign" => "adwords",
        "utm_term" => "api+tooling",
        "utm_content" => "landing"
    ),
    "metadata" => array(
        "org_name" => "Acme, Inc",
        "plan_name" => "Free",
        "deal_stage" => "Lead",
        "mrr" => 24000,
        "demographics" => array(
            "alexa_ranking" => 500000,
            "employee_count" => 47
        )
    )
);

$companies = array($companyA);

$middleware = new MoesifLaravel();
$middleware->updateCompaniesBatch($companies);

metadata 字段可以是您想要在公司上设置的任何自定义数据。需要 company_id 字段。

Moesif Laravel SDK 的积分

  • 队列和通过分叉非阻塞进程发送数据的一部分是基于 Mixpanel 的 PHP 客户端代码,该代码在 Apache License,版本 2.0 下开源。

其他提示

  • 发送数据使用的是 exec() 和 cURL 命令的 (即非阻塞方式)。Php exec() 命令可能成功,但 cURL 本身可能存在 401 错误。因此,在集成后,如果您没有看到事件和数据在您的 Moesif Dash 中显示。请开启调试选项,然后 cURL 命令本身将被记录。您可以执行该 cURL 命令并查看问题所在。最常见的事情要检查的是应用程序 ID 是否设置正确。

如果您的 exec() 作为禁用函数,可以设置配置选项 disableForkingtrue 以使用 curl PHP 扩展向 Moesif 发送数据。

故障排除

exec() 必须存在/exec() 必须启用

默认情况下,Moesif 以异步方式通过创建进程来记录 API 调用,这需要您的 PHP 环境启用了 exec()。为了获得最佳性能,建议确保您的托管环境已启用 exec()。

如果您无法启用 exec(例如对于共享托管环境),您可以通过将以下内容添加到您的 moesif.php 文件中来禁用进程创建。

return [
    'applicationId' => 'Your Moesif Application Id',
    'disableForking' => true,
];

需要 PHP JSON 扩展。

请确保安装带有 JSON 扩展启用的 PHP 更多信息

需要 PHP cURL 扩展。

当您禁用了进程创建且未启用 cURL PHP 扩展时,会出现此错误。建议的修复方法是,在您的 moesif.php 中将 disableForking 设置为 false 以启用进程创建。否则,请确保已启用 PHP CURL 扩展。 更多信息

在 Moesif 中看不到任何事件

由于 Moesif 会创建进程,您可能看不到子进程的所有错误。事件未显示的常见原因是不正确的应用程序 ID。要查看调试日志,您可以在您的 moesif.php 中添加以下内容

// In config/moesif.php

return [
    //
    'applicationId' => 'Your Moesif Application Id',
    'debug' => true,
];

使用 Moesif 集成的 Laravel 应用进行测试

Moesif Laravel 测试

一个集成了 Moesif 的 Laravel 应用示例

Moesif Laravel 示例

确保在更改配置后更新缓存

如果您启用了配置缓存,在您更新配置后,请务必再次运行 php artisan config:cache 以确保配置已更新。

其他集成

要查看更多关于集成选项的文档,请访问 集成选项文档

从 v1.x.x 迁移到 v2.x.x 的迁移指南

现在 v2.x.x 支持 Laravel 配置缓存。但是,config:cache 不允许在配置文件中使用函数闭包(请参阅 GitHub 上的问题),因此 v2.x.x 中的 SDK 配置已更改。要迁移,您需要将 config/moesif.php 中的任何函数移动到单独的类,例如 CustomMoesifConfig。然后,使用 configClass 引用此类。

例如,如果您之前有这些

$identifyUserId = function($request, $response) {
    // Your custom code that returns a user id string
    $user = $request->user();
    if ($request->user()) {
        return $user->id;
    }
    return NULL;
};

return [
  ...,
  'identifyUserId' => $identifyUserId,
]

在 V2.X.X 中,您将这样做

  • 创建一个新类,如下所示
namespace MyApp\MyConfigs;

class CustomMoesifConfig
{
    public function identifyUserId($request, $response) {
      if (is_null($request->user())) {
        return null;
      } else {
        $user = $request->user();
        return $user['id'];
      }
    }

    // add other methods for closure based configs.
}
  • 在配置文件夹中的您的 moesif.php 文件中
return [
  ...,
  'configClass' => 'MyApp\\MyConfigs\\CustomMoesifConfig',
]