Ajouter des informations additionnelles aux logs d'erreur Symfony

Publié le 19/03/2019 • Mis à jour 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 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 string $appEnv,
        private string $appServer,
        private string $appVersion,
        private RequestStack $requestStack)
    {
    }

    /**
     * Add environment extra data to the log record to ease debug.
     *
     * @param array<string,mixed> $record
     *
     * @return array<string,mixed>
     */
    public function __invoke(array $record): array
    {
        /** @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();
            }

            $referer = u($request->headers->get('referer'))->trim();
            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