PHP for dynamically changing the log level


Code Solution

<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Create a logger
$logger = new Logger('MyLogger');

// Create a stream handler
$stream = new StreamHandler('my.log', Logger::INFO);

// Add the handler to the logger
$logger->pushHandler($stream);

// Set the log level dynamically
$logger->setLevel(Logger::WARNING);

// Log a message
$logger->warning('This is a warning message');

Explanation

This code demonstrates how to dynamically change the log level in PHP using the Monolog library.

The $logger->setLevel() method takes a log level constant as its argument, which can be one of the following:

  • Logger::DEBUG
  • Logger::INFO
  • Logger::NOTICE
  • Logger::WARNING
  • Logger::ERROR
  • Logger::CRITICAL
  • Logger::ALERT
  • Logger::EMERGENCY

By setting the log level, we can control which messages are logged to the file. For example, if we set the log level to Logger::WARNING, only messages with a level of Logger::WARNING or higher will be logged.

In this example, we create a logger and add a stream handler to it. We then set the log level to Logger::WARNING and log a message with a level of Logger::WARNING. The message will be logged to the file my.log.

This code can be used to dynamically change the log level of an application at runtime. This can be useful for debugging or for controlling the amount of logging that is generated.