PHP: Adding Application insights into your PHP

apt install composer
composer require microsoft/application-insights

Create a new file:

<?php

$telemetryClient = new \ApplicationInsights\Telemetry_Client();
$context = $telemetryClient->getContext();
$script_start_time=microtime(true);
register_shutdown_function('myshutdown');
// Necessary
$context->setInstrumentationKey('yourkey');

function myshutdown()
{
        global $script_start_time,$telemetryClient;

        $url = $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
        $requestName = $_SERVER["SCRIPT_FILENAME"];
        $duration = microtime(true)-$script_start_time; 
        $extra_data=array();
        $extra_data["client.user_agent"]=@$_SERVER['HTTP_USER_AGENT'];
        $extra_data["client.client_ip"]=@$_SERVER['REMOTE_ADDR'];
        $telemetryClient->trackRequest($requestName, $url, @$_SERVER["REQUEST_TIME"], $duration*1000, http_response_code(),true,$extra_data );
        $telemetryClient->flush();

}

?>

Modify file vendor/microsoft/application-insights/ApplicationInsights/Channel/Telemetry_Channel.php

 public function send($options = array(), $sendAsync = false)
    {
        $response = null;
        $useGuzzle = $this->_client !== null;
        if (count($this->_queue) == 0)
        {
            return;
        }

        $serializedTelemetryItem = $this->getSerializedQueue();

        if($this->_sendGzipped && $useGuzzle)
        {
            $headersArray = array(
                'Content-Encoding' => 'gzip',
            );
            $body = gzencode($serializedTelemetryItem);
        }
        else
        {
            $headersArray = array(
                'Accept' => 'application/json',
                'Content-Type' => 'application/json; charset=utf-8'
            );
            $body = utf8_encode($serializedTelemetryItem);
        }
        //Thao
        $headersArray["User-Agent"]=$_SERVER["HTTP_USER_AGENT"];
       //Thao
        if ($useGuzzle)
        {

Leave a Reply

Your email address will not be published. Required fields are marked *