I've got a simple class that allows me to write to any log file:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class Mylog
{
public function __construct($log, $level = 'debug')
{
$this->monolog = new Logger($log);
$level = constant('Logger::'.strtoupper($level));
$this->monolog->pushHandler(new StreamHandler(storage_path('logs/'.$log.'-'.date('Y-m-d').'.txt')), $level);
}
public function __call($method, $arguments)
{
$this->monolog->{$method}($arguments[0]);
}
}
This gives me the error: constant(): Couldn't find constant Logger::DEBUG
However, when pushing the handler, if I replace $level with simply Logger::DEBUG, it works. Why is it not finding the constant when it does, in fact, exist?
The class name inside a string like in the argument to the constant()
function must be fully qualified. When you do Logger::DEBUG it works because the class is use'd
, so it resolves as Monolog\\Logger::DEBUG
but in the string it just remains Logger::DEBUG
and that obviously does not exist.
Therefore the solution is simply to use the fully qualified name within strings, ie
$level = constant('Monolog\Logger::'.strtoupper($level));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.