💾 Archived View for code.lanterne.chilliet.eu › vendor › mcmic › gemini-server › src › RequestCsvLog… captured on 2023-09-08 at 15:57:48.

View Raw

More Information

⬅️ Previous capture (2021-12-17)

-=-=-=-=-=-=-

<?php

declare(strict_types=1);

namespace MCMic\Gemini;

use Psr\Log;

class RequestCsvLogger extends RequestLogger
{
    protected string $csvPath;

    public function __construct(string $csvPath = 'requestlog.csv', ?Log\LoggerInterface $logger = null)
    {
        parent::__construct($logger);
        $path = realpath($csvPath);
        if ($path === false) {
            $dir = realpath(dirname($csvPath));
            if ($dir === false) {
                $this->csvPath = $csvPath;
            } else {
                $this->csvPath = $dir . '/' . basename($csvPath);
            }
        } else {
            $this->csvPath = $path;
        }
        $this->logger->info('Logging requests as CSV into ' . $this->csvPath);
    }

    /**
     * @param string|Request $request
     */
    public function logException(string $peername, $request, Exception $e): void
    {
        parent::logException($peername, $request, $e);
        $handle = fopen($this->csvPath, 'a');
        if ($handle === false) {
            $this->logger->notice('Failed to open ' . $this->csvPath);
        } else {
            fputcsv($handle, [date('c'), static::hashPeername($peername), (string)$request, (string)$e->getCode(), $e->getMessage()]);
            fclose($handle);
        }
    }

    public function logResponse(string $peername, Request $request, Response $response): void
    {
        parent::logResponse($peername, $request, $response);
        $handle = fopen($this->csvPath, 'a');
        if ($handle === false) {
            $this->logger->notice('Failed to open ' . $this->csvPath);
        } else {
            fputcsv($handle, [date('c'), static::hashPeername($peername), (string)$request, (string)$response->status, $response->meta]);
            fclose($handle);
        }
    }
}