Ajouter des informations additionnelles aux logs d'erreur Symfony

Publié le 19/03/2019 • Actualisé le 19/03/2019


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Quand un bug survient, il est parfois difficile d'en identifier la source. Avoir plus de contexte permet de trouver et de pouvoir reproduire les problèmes plus facilement. Dans l'exemple suivant nous allons ajouter quelques informations de configuration de l'application. Et, si un objet Request est disponible nous allons ajouter l'URI courante ainsi que le referer s'ils existent. Le service EnvProcessor doit être tagué avec monolog.processor et déclaré dans le fichier services.yaml. Enfin vous devrez "binder" ces paramètres pour qu'ils puissent être identifiés. (uniquement le paramètre $appEnv (APP_ENV) est commun aux applications Symfony4 / Flex)


<?php

declare(strict_types=1);

namespace App\Log\Processor;

use Monolog\LogRecord;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

use function Symfony\Component\String\u;

/**
 * Add extra data to logs.
 *
 * @see http://symfony.com/doc/current/logging/processors.html
 */
final class EnvProcessor
{
    /**
     * Check out the doc to see you to bind your parameters. In this case:
     * - "app_env" and "app_server" come from the ".env" file and are made available in services.yaml:
     * - app_env: '%env(APP_ENV)%'
     * - "app_version" comes from "services.yaml"
     * - "$requestStack" is the standard Symfony value object.
     *
     * @see https://symfony.com/doc/current/service_container.html#binding-arguments-by-name-or-type
     */
    public function __construct(
        private readonly string $appEnv,
        private readonly string $appServer,
        private readonly string $appVersion,
        private readonly RequestStack $requestStack)
    {
    }

    /**
     * Add environment extra data to the log record to ease debug.
     */
    public function __invoke(LogRecord $record): LogRecord
    {
        /** @var array<string> $extra */
        $extra = $record['extra'] ?? [];
        $extra['app_server'] = $this->appServer;
        $extra['app_env'] = $this->appEnv;
        $extra['app_version'] = $this->appVersion;

        $request = $this->requestStack->getCurrentRequest();
        if ($request instanceof Request) {
            $uri = u($request->getUri())->trim();
            if (!$uri->isEmpty()) {
                $extra['uri'] = $uri->toString();
            }

            // prevents hacking attempts
            try {
                $referer = u($request->headers->get('referer'))->trim();
            } catch (\Exception) {
                $referer = u('Referer is an invalid UTF8 string.');
            }

            if (!$referer->isEmpty()) {
                $extra['referer'] = $referer->toString();
            }

            $ip = u($request->getClientIp())->trim();
            if (!$ip->isEmpty()) {
                $extra['ip'] = $ip->toString();
                try {
                    $extra['host'] = gethostbyaddr($extra['ip']);
                } catch (\Exception) {
                    $extra['host'] = 'Exception when resolving host';
                }
            }
        }

        $record['extra'] = $extra;

        return $record;
    }
}

 Plus sur Stackoverflow   Lire la doc  Snippet aléatoire

  Travaillez avec moi !