| 1 |
<?php |
| 2 |
/** |
| 3 |
* Copyright 2024 Google Inc. All Rights Reserved. |
| 4 |
* |
| 5 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
* you may not use this file except in compliance with the License. |
| 7 |
* You may obtain a copy of the License at |
| 8 |
* |
| 9 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
* |
| 11 |
* Unless required by applicable law or agreed to in writing, software |
| 12 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
* See the License for the specific language governing permissions and |
| 15 |
* limitations under the License. |
| 16 |
*/ |
| 17 |
|
| 18 |
namespace Google\Auth\Logging; |
| 19 |
|
| 20 |
use InvalidArgumentException; |
| 21 |
use Psr\Log\LoggerInterface; |
| 22 |
use Psr\Log\LoggerTrait; |
| 23 |
use Psr\Log\LogLevel; |
| 24 |
use Stringable; |
| 25 |
|
| 26 |
/** |
| 27 |
* A basic logger class to log into stdOut for GCP logging. |
| 28 |
* |
| 29 |
* @internal |
| 30 |
*/ |
| 31 |
class StdOutLogger implements LoggerInterface |
| 32 |
{ |
| 33 |
use LoggerTrait; |
| 34 |
|
| 35 |
/** |
| 36 |
* @var array<string,int> |
| 37 |
*/ |
| 38 |
private array $levelMapping = [ |
| 39 |
LogLevel::EMERGENCY => 7, |
| 40 |
LogLevel::ALERT => 6, |
| 41 |
LogLevel::CRITICAL => 5, |
| 42 |
LogLevel::ERROR => 4, |
| 43 |
LogLevel::WARNING => 3, |
| 44 |
LogLevel::NOTICE => 2, |
| 45 |
LogLevel::INFO => 1, |
| 46 |
LogLevel::DEBUG => 0, |
| 47 |
]; |
| 48 |
private int $level; |
| 49 |
|
| 50 |
/** |
| 51 |
* Constructs a basic PSR-3 logger class that logs into StdOut for GCP Logging |
| 52 |
* |
| 53 |
* @param string $level The level of the logger instance. |
| 54 |
*/ |
| 55 |
public function __construct(string $level = LogLevel::DEBUG) |
| 56 |
{ |
| 57 |
$this->level = $this->getLevelFromName($level); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* {@inheritdoc} |
| 62 |
*/ |
| 63 |
public function log($level, string|Stringable $message, array $context = []): void |
| 64 |
{ |
| 65 |
if ($this->getLevelFromName($level) < $this->level) { |
| 66 |
return; |
| 67 |
} |
| 68 |
|
| 69 |
print($message . "\n"); |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* @param string $levelName |
| 74 |
* @return int |
| 75 |
* @throws InvalidArgumentException |
| 76 |
*/ |
| 77 |
private function getLevelFromName(string $levelName): int |
| 78 |
{ |
| 79 |
if (!array_key_exists($levelName, $this->levelMapping)) { |
| 80 |
throw new InvalidArgumentException('The level supplied to the Logger is not valid'); |
| 81 |
} |
| 82 |
|
| 83 |
return $this->levelMapping[$levelName]; |
| 84 |
} |
| 85 |
} |
| 86 |
|