Disable a log handler temporarily in Symfony

« Back to overview

Symfony has a great log system using monolog. But it may cause problems.

Say, you have a console command that outputs massive logs.
And you have CloudWatch logging enabled (with for example Maxbanton\Cwh\Handler\CloudWatch) but you do not want to stream all the logs to CloudWatch.

You can remove a specific class of log handlers from monolog in Symfony by using this code snippet:

use Maxbanton\Cwh\Handler\CloudWatch as CloudWatchLogHandler;

     * @param \Monolog\Logger | \stdClass $logger
     * @return bool
    protected static function disableCloudWatchLogHandler($logger) : bool {
        if (!$logger instanceof \Monolog\Logger) {
            $logger->warning('Cannot disable CloudWatch log handler because a monolog logger is needed');
            return false;
        // replace the handlers
        $disabled = false;
        $handlers = $logger->getHandlers();
        $newHandlers  = [];
        foreach ($handlers as $key => $handler) {
            if (!$handler instanceof CloudWatchLogHandler) {
                $newHandlers[] = $handler;
            } else {
                $disabled = true;
        $logger->warning(sprintf('CloudWatch log handler %s disabled', $disabled ? 'was' : 'NOT'));
        return $disabled;

   // static::disableCloudWatchLogHandler($this->logger);