phpconstantsmonologclass-constants

How to use a global constant instead of a class constant in PHP version 5.6


I'm using Monolog to create my app's logging system. In the core app file, after I create a new Monolog object, I need to select the log level that I want to print in the log file. I want to use a global constant LOG_LEVEL which could be 'DEBUG', 'INFO', etc. I need the Monolog class to treat its value as a class constant.

// content of config.php
// Here I declare the constants in a separate file called 'config.php'
define("LOG_FILE", "patch/to/my/log.log");
define("LOG_LEVEL", "ERROR");

// content of app.php
require 'config.php';
require 'vendor/autoload.php';

$container['logger'] = function($c) {
    $logger = new \Monolog\Logger('logger');
    error_log('log level ' . LOG_LEVEL); // prints 'log level ERROR'

    $fileHandler = new \Monolog\Handler\StreamHandler(LOG_FILE, $logger::LOG_LEVEL); // here I get the error 'Undefined class constant LOG_LEVEL'
    //the normal syntax would be '$logger::ERROR' in this case and that works fine

    $logger->pushHandler($fileHandler);
    return $logger;
};

I need the 'LOG_LEVEL' constant to be used as 'ERROR' by the monolog class, not as 'LOG_LEVEL'. What am I doing wrong here, been searching an answer for hours now without any luck.


Solution

  • You are now doing $logger::LOG_LEVEL, which is taking the 'LOG_LEVEL' out of the class whichever $logger is (in this case a \Monolog\Logger). That doesn't have a static variable named LOG_LEVEL, thus you get the undefined.
    You have just have 'LOG_LEVEL' defined, out of any class, so:

     $fileHandler = new \Monolog\Handler\StreamHandler(LOG_FILE, LOG_LEVEL); 
    

    Fancy solution:

    You could do a static class and include that in your main page:

    Class CONFIG {
        public static $LOG_LEVEL = 'default Value';
    }
    
    // Then you can use this anywhere:
    CONFIG::$LOG_LEVEL
    $fileHandler = new \Monolog\Handler\StreamHandler(LOG_FILE, CONFIG::$LOG_LEVEL); 
    

    The advantage of this is having only one file for configs, not scattered across all kinds of files, which'll become very annoying very fast.