Google Cloud Stackdriver and monolog Symfony

半城伤御伤魂 提交于 2021-01-28 09:16:43

问题


I'm working with Google Cloud (GKE) and I want to use their system for log and monitor (Stackdriver). My projet is under php Symfony3. I'm searching how to log to stackdriver some logs of my symfony project.

I saw that there is an offical lib :

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

And a PSR-3 class :

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

My question is, how to integrate that in my config.yml with monolog ?


回答1:


I did this by doing the following:

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

In the config, I used a custom handler:

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

Register the handler service:

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

Here's the handler class I used:

<?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];
    }
}


来源:https://stackoverflow.com/questions/41676196/google-cloud-stackdriver-and-monolog-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!