0

我正在使用Google Cloud(GKE),我想使用他們的系統進行日誌和監視(Stackdriver)。我的工程是在php Symfony3下。我正在尋找如何登錄stackdriver symfony項目的一些日誌。Google Cloud Stackdriver和monolog Symfony

我看到有一個官方的lib:

https://github.com/GoogleCloudPlatform/google-cloud-php

而一個PSR-3類:

http://googlecloudplatform.github.io/google-cloud-php/#/docs/v0.20.1/logging/psrlogger

我的問題是,如何整合了在我的配置。 yml與monolog?

回答

3

我通過執行以下操作做到這一點:

composer require "google/cloud":"~0.20" 

在配置,我用了一個自定義處理程序:

monolog: 
    handlers: 
     main: 
      type: service 
      id: stackdriver_handler 

註冊處理程序服務:

services: 
    stackdriver_handler: 
     class: Acme\MyBundle\Monolog\StackdriverHandler 

這裏的處理器類我使用:

<?php 

namespace Acme\MyBundle\Monolog\Handler; 

use Google\Cloud\Logging\LoggingClient; 
use Monolog\Handler\PsrHandler; 
use Monolog\Logger; 
use Psr\Log\LoggerInterface; 

class StackdriverHandler extends PsrHandler 
{ 
    /** 
    * @var LoggerInterface[] 
    */ 
    protected $loggers; 

    /** 
    * @var LoggingClient 
    */ 
    protected $client; 

    /** 
    * @var string 
    */ 
    protected $name; 

    /** 
    * StackdriverHandler constructor. 
    * 
    * @param LoggerInterface $projectId 
    * @param bool   $name 
    * @param bool|int  $level 
    * @param bool   $bubble 
    */ 
    public function __construct($projectId, $name, $level = Logger::DEBUG, $bubble = true) 
    { 
     $this->client = new LoggingClient(
      [ 
       'projectId' => $projectId, 
      ] 
     ); 

     $this->name = $name; 
     $this->level = $level; 
     $this->bubble = $bubble; 
    } 

    /** 
    * {@inheritdoc} 
    */ 
    public function handle(array $record) 
    { 
     if (!$this->isHandling($record)) { 
      return false; 
     } 

     $this->getLogger($record['channel'])->log(strtolower($record['level_name']), $record['message'], $record['context']); 

     return false === $this->bubble; 
    } 

    /** 
    * @param $channel 
    * 
    * @return LoggerInterface 
    */ 
    protected function getLogger($channel) 
    { 
     if (!isset($this->loggers[$channel])) { 
      $this->loggers[$channel] = $this->client->psrLogger($this->name, ['labels' => ['context' => $channel]]); 
     } 

     return $this->loggers[$channel]; 
    } 
}