簡體   English   中英

Google Cloud Stackdriver 和 Monolog Symfony

[英]Google Cloud Stackdriver and monolog Symfony

我正在使用 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 中?

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM