PHP code example of codeinternetapplications / monolog-stackdriver

1. Go to this page and download the library: Download codeinternetapplications/monolog-stackdriver library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

codeinternetapplications / monolog-stackdriver example snippets


$context['stackdriver'] = [
    // stackdriver related entry options
];

define('GOOGLE_APPLICATION_CREDENTIALS', '/path/to/service-account-key-file.json'); 
define('GOOGLE_CLOUD_PROJECT', 'eg-my-project-id-148223');

use Monolog\Logger;
use CodeInternetApplications\MonologStackdriver\StackdriverHandler;

// ( ... )

// GCP Project ID
$projectId = 'eg-my-project-id-148223';

// See Google\Cloud\Logging\LoggingClient::__construct
$loggingClientOptions = [
    'keyFilePath' => '/path/to/service-account-key-file.json'
];

// init handler
$stackdriverHandler = new StackdriverHandler(
    $projectId,
    $loggingClientOptions
);

// init logger with StackdriverHandler
$logger = new Logger('stackdriver', [$stackdriverHandler]);

// basic info log with contextual data
$logger->info('New order', ['orderId' => 1001]);

// ( ... )

// add specific log entry options, eg labels
$context = ['orderId' => 1001];

// add a 'stackdriver' entry to the context to append
// log entry specific options
$context['stackdriver'] = [
    'labels' => [
        'action' => 'paid'
    ]
];
$logger->info('Order update', $context);

// ( ... )

// add specific log entry options, eg labels and operation
$context = ['orderId' => 1001];
$context['stackdriver'] = [
    'labels' => [
        'order' => 'draft'
    ],
    'operation' => [
        'id' => 'order-1001',
        'first' => true,
        'last' => false
    ]
];
$logger->info('Order update', $context);

// update both label and operation
$context['stackdriver'] = [
    'labels' => [
        'order' => 'paid'
    ],
    'operation' => [
        'id' => 'order-1001',
        'first' => false,
        'last' => false
    ]
];
$logger->info('Order update', $context);

// update both label and operation again
$context['stackdriver'] = [
    'labels' => [
        'order' => 'fulfilled'
    ],
    'operation' => [
        'id' => 'order-1001',
        'first' => false,
        'last' => true
    ]
];
$logger->info('Order update', $context);