|
| 1 | +<?php |
| 2 | +/* |
| 3 | + * Copyright 2023-present MongoDB, Inc. |
| 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 | + * https://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 MongoDB; |
| 19 | + |
| 20 | +use MongoDB\Driver\Logging\Logger as DriverLoggerInterface; |
| 21 | +use Psr\Log\LoggerInterface as PsrLoggerInterface; |
| 22 | +use Psr\Log\LogLevel as PsrLogLevel; |
| 23 | + |
| 24 | +class PsrLogAdapter implements DriverLoggerInterface |
| 25 | +{ |
| 26 | + private PsrLoggerInterface $psrLogger; |
| 27 | + |
| 28 | + public function __construct(PsrLoggerInterface $psrLogger) |
| 29 | + { |
| 30 | + $this->psrLogger = $psrLogger; |
| 31 | + } |
| 32 | + |
| 33 | + public function log(int $level, string $domain, string $message): void |
| 34 | + { |
| 35 | + $this->psrLogger->log( |
| 36 | + $this->driverLevelToPsrLevel($level), |
| 37 | + $domain . ': ' . $message, |
| 38 | + ); |
| 39 | + } |
| 40 | + |
| 41 | + // TODO: Refactor this method as a private const array map on PsrLogAdapter |
| 42 | + private function driverLevelToPsrLevel(int $level): string |
| 43 | + { |
| 44 | + switch ($level) { |
| 45 | + /* libmongoc considers "critical" less severe than "error" so route |
| 46 | + * both levels to "error" in the PSR logger. */ |
| 47 | + case DriverLoggerInterface::LEVEL_ERROR: |
| 48 | + case DriverLoggerInterface::LEVEL_CRITICAL: |
| 49 | + return PsrLogLevel::ERROR; |
| 50 | + |
| 51 | + case DriverLoggerInterface::LEVEL_WARNING: |
| 52 | + return PsrLogLevel::WARNING; |
| 53 | + |
| 54 | + case DriverLoggerInterface::LEVEL_MESSAGE: |
| 55 | + return PsrLogLevel::NOTICE; |
| 56 | + |
| 57 | + case DriverLoggerInterface::LEVEL_INFO: |
| 58 | + return PsrLogLevel::INFO; |
| 59 | + |
| 60 | + /* PSR does not define a "trace" level, so route both levels to |
| 61 | + * "debug". That said, trace logging is very verbose and should not |
| 62 | + * be encouraged when using a PSR logger. */ |
| 63 | + case DriverLoggerInterface::LEVEL_DEBUG: |
| 64 | + case DriverLoggerInterface::LEVEL_TRACE: |
| 65 | + return PsrLogLevel::DEBUG; |
| 66 | + |
| 67 | + /* A default case is intentionally not handled since libmongoc and |
| 68 | + * PHPC should avoid emitting bogus levels; however, we can consider |
| 69 | + * throwing an UnexpectedValueException here. */ |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments