summaryrefslogtreecommitdiff
path: root/vendor/open-telemetry/sdk/Logs/SimplePsrFileLogger.php
blob: 9d9d55de6d293f0fe75aceb4968ab9cd657802ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php

declare(strict_types=1);

namespace OpenTelemetry\SDK\Logs;

use Psr\Log\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\LoggerTrait;
use Psr\Log\LogLevel;
use ReflectionClass;
use Throwable;

class SimplePsrFileLogger implements LoggerInterface
{
    use LoggerTrait;

    private const DEFAULT_LOGGER_NAME = 'otel';

    private static ?array $logLevels = null;

    private string $filename;

    private string $loggerName ;

    /**
     * @param string $filename
     */
    public function __construct(string $filename, string $loggerName = self::DEFAULT_LOGGER_NAME)
    {
        $this->filename = $filename;
        $this->loggerName = $loggerName;
    }

    /**
     * @psalm-suppress MoreSpecificImplementedParamType
     */
    public function log($level, $message, array $context = []): void
    {
        $level = strtolower($level);

        if (!in_array($level, self::getLogLevels(), true)) {
            throw new InvalidArgumentException(
                sprintf('Invalid Log level: "%s"', $level)
            );
        }

        file_put_contents($this->filename, $this->formatLog((string) $level, (string) $message, $context), FILE_APPEND);
    }

    /**
     * @param string $level
     * @param string $message
     * @param array $context
     * @return string
     */
    private function formatLog(string $level, string $message, array $context = []): string
    {
        try {
            $encodedContext = json_encode($context, JSON_THROW_ON_ERROR);
        } catch (Throwable $t) {
            $encodedContext = sprintf('(Could not encode context: %s)', $t->getMessage());
        }

        return sprintf(
            '[%s] %s %s: %s %s%s',
            date(DATE_RFC3339_EXTENDED),
            $this->loggerName,
            $level,
            $message,
            $encodedContext,
            PHP_EOL
        );
    }

    /**
     * @return array
     */
    private static function getLogLevels(): array
    {
        return self::$logLevels ?? self::$logLevels = (new ReflectionClass(LogLevel::class))->getConstants();
    }
}