You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
engelsystem/src/Logger/EngelsystemLogger.php

84 lines
2.0 KiB
PHTML

7 years ago
<?php
namespace Engelsystem\Logger;
use Engelsystem\Models\LogEntry;
7 years ago
use Psr\Log\AbstractLogger;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LogLevel;
class EngelsystemLogger extends AbstractLogger
{
protected $allowedLevels = [
LogLevel::ALERT,
LogLevel::CRITICAL,
LogLevel::DEBUG,
LogLevel::EMERGENCY,
LogLevel::ERROR,
LogLevel::INFO,
LogLevel::NOTICE,
LogLevel::WARNING,
];
/** @var LogEntry */
protected $log;
public function __construct(LogEntry $log)
{
$this->log = $log;
}
7 years ago
/**
* Logs with an arbitrary level.
*
* @TODO: Implement $context['exception']
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @throws InvalidArgumentException
*/
public function log($level, $message, array $context = [])
{
if (!$this->checkLevel($level)) {
throw new InvalidArgumentException('Unknown log level: ' . $level);
7 years ago
}
$message = $this->interpolate($message, $context);
$this->log->create(['level' => $level, 'message' => $message]);
7 years ago
}
/**
* Interpolates context values into the message placeholders.
*
* @param string $message
* @param array $context
* @return string
*/
protected function interpolate($message, array $context = [])
{
foreach ($context as $key => $val) {
// check that the value can be casted to string
if (is_array($val) || (is_object($val) && !method_exists($val, '__toString'))) {
continue;
}
// replace the values of the message
$message = str_replace('{' . $key . '}', $val, $message);
}
return $message;
}
/**
* @param string $level
* @return bool
*/
protected function checkLevel($level)
{
return in_array($level, $this->allowedLevels);
}
}