Skip to content

Commit

Permalink
Allow set log level with integers
Browse files Browse the repository at this point in the history
  • Loading branch information
natanfelles committed Mar 22, 2024
1 parent d176238 commit 6925e1d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ abstract class Logger
* Logger constructor.
*
* @param string $destination
* @param LogLevel $level
* @param int|LogLevel $level
* @param array<mixed> $config
*/
public function __construct(
string $destination,
LogLevel $level = LogLevel::DEBUG,
LogLevel|int $level = LogLevel::DEBUG,
array $config = []
) {
$this->setDestination($destination);
Expand Down Expand Up @@ -86,18 +86,21 @@ protected function getConfig() : array
/**
* Logs with an arbitrary level.
*
* @param LogLevel $level
* @param int|LogLevel $level
* @param string $message
* @param array<string> $context
*
* @return bool
*/
public function log(LogLevel $level, string $message, array $context = []) : bool
public function log(LogLevel|int $level, string $message, array $context = []) : bool
{
$debug = isset($this->debugCollector);
if ($debug) {
$start = \microtime(true);
}
if (\is_int($level)) {
$level = LogLevel::from($level);
}
$this->lastLog = null;
if ($level->value < $this->getLevel()->value) {
return true;
Expand Down Expand Up @@ -263,8 +266,11 @@ public function getLevel() : LogLevel
return $this->level;
}

public function setLevel(LogLevel $level) : static
public function setLevel(LogLevel|int $level) : static
{
if (\is_int($level)) {
$level = LogLevel::from($level);
}
$this->level = $level;
return $this;
}
Expand Down
25 changes: 25 additions & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,29 @@ public function testLastLogOnDisabledLevel() : void
$this->logger->logDebug('foo');
self::assertNull($this->logger->getLastLog());
}

public function testLogLevel() : void
{
self::assertSame(LogLevel::DEBUG, $this->logger->getLevel());
$this->logger->setLevel(LogLevel::INFO);
self::assertSame(LogLevel::INFO, $this->logger->getLevel());
$this->logger->setLevel(3);
self::assertSame(LogLevel::WARNING, $this->logger->getLevel());
$this->expectException(\ValueError::class);
$this->expectExceptionMessage(
'23 is not a valid backing value for enum Framework\Log\LogLevel'
);
$this->logger->setLevel(23);
}

public function testLogWithInteger() : void
{
self::assertTrue($this->logger->log(7, 'Foo bar'));
self::assertSame(LogLevel::EMERGENCY, $this->logger->getLastLog()->level);
$this->expectException(\ValueError::class);
$this->expectExceptionMessage(
'10 is not a valid backing value for enum Framework\Log\LogLevel'
);
$this->logger->setLevel(10);
}
}

0 comments on commit 6925e1d

Please sign in to comment.