halloverden/azure-application-insights

此项目扩展了应用程序洞察API界面以支持PHP。

0.1.4 2022-06-22 10:22 UTC

This package is auto-updated.

Last update: 2024-09-22 15:41:28 UTC


README

该项目是从windows的官方php SDK分叉而来,并在此基础上构建,但现已不再维护。目前,它仅支持异常记录。

关于

状态

尽管微软过去曾为此做出过贡献,但此SDK目前既不维护也不受微软支持。请注意,Azure Monitor仅在使用支持的SDK时提供支持。

要求

  • PHP版本 ^7.1

安装

请确保已全局安装Composer,如Composer文档中的安装章节所述。

打开命令行,进入您的项目目录并执行

$ composer require halloverden/application-insights-sdk

用法

安装后,您可以将异常遥测数据发送到应用程序洞察。以下是一些示例。

注意:在您可以将数据发送到应用程序洞察之前,您需要获取一个仪表化密钥。有关更多信息,请参阅获取应用程序洞察仪表化密钥部分。

初始化客户端并设置仪表化密钥和其他可选配置

$telemetryClient = new \ApplicationInsights\Telemetry_Client();
$context = $telemetryClient->getContext();

// Necessary
$context->setInstrumentationKey('YOUR INSTRUMENTATION KEY');

// Optional
$context->getSessionContext()->setId(session_id());
$context->getUserContext()->setId('YOUR USER ID');
$context->getApplicationContext()->setVer('YOUR VERSION');
$context->getLocationContext()->setIp('YOUR IP');

// Start tracking throwables
$telemetryClient->trackException($throwable);
$telemetryClient->flush();

设置操作上下文

为了正确报告应用程序洞察,您需要设置操作上下文,即对请求的引用

$telemetryClient->getContext()->getOperationContext()->setId('XX');
$telemetryClient->getContext()->getOperationContext()->setName('GET Index');

发送带有自定义属性和指标的异常遥测数据

try
{
    // Do something to throw an exception
}
catch (\Exception $ex)
{
    $telemetryClient->trackException($ex, ['InlineProperty' => 'test_value'], ['duration_inner' => 42.0]);
    $telemetryClient->flush();
}

将客户端设置为在发送前压缩数据

$telemetryClient->getChannel()->setSendGzipped(true);

注册异常处理程序

class Handle_Exceptions
{
    private $_telemetryClient;

    public function __construct()
    {
        $this->_telemetryClient = new \ApplicationInsights\Telemetry_Client();
        $this->_telemetryClient->getContext()->setInstrumentationKey('YOUR INSTRUMENTATION KEY');

        set_exception_handler(array($this, 'exceptionHandler'));
    }

    function exceptionHandler(\Exception $exception)
    {
        if ($exception != NULL)
        {
            $this->_telemetryClient->trackException($exception);
            $this->_telemetryClient->flush();
        }
    }
}