1

我正在使用 Google Cloud (GKE),我想使用他们的系统进行日志和监控 (Stackdriver)。我的项目在 php Symfony3 下。我正在搜索如何将我的 symfony 项目的一些日志记录到 stackdriver。

我看到有一个官方库:

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

还有一个 PSR-3 类:

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

我的问题是,如何将它与 monolog 集成到我的 config.yml 中?

4

1 回答 1

7

我通过执行以下操作来做到这一点:

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];
    }
}
于 2017-02-08T01:21:48.823 回答