Chain of responsability for logging on PHP

WINW > Software Development > Design Patterns > Chain of responsability for logging on PHP

Using the Chain of Responsibility pattern for logging in PHP can be quite useful for handling different levels or types of log messages and their destinations. Here’s an example of how you might implement this pattern for logging:

Logger Interface

First, create an interface for the logger:

interface Logger {
  public function setNext(Logger $logger): Logger;
  public function logMessage($level, $message);
}

Abstract Logger

Create an abstract class that implements the Logger interface and provides the default behavior for setting the next logger:

abstract class AbstractLogger implements Logger {
    protected $nextLogger;

    public function setNext(Logger $logger): Logger {
        $this->nextLogger = $logger;
        return $logger;
    }

    public function logMessage($level, $message) {
        // This is where you handle the log message
        $this->write($level, $message);

        // Pass the message to the next logger in the chain
        if ($this->nextLogger !== null) {
            $this->nextLogger->logMessage($level, $message);
        }
    }

    abstract protected function write($level, $message);
}

Concrete Loggers

Create concrete logger classes that extend the abstract logger and implement the write method for specific logging behaviors:

class ConsoleLogger extends AbstractLogger {
    protected function write($level, $message) {
        // Logging to the console
        echo "Console Logger: [$level] $message\n";
    }
}

class FileLogger extends AbstractLogger {
    protected function write($level, $message) {
        // Logging to a file
        $file = fopen('log.txt', 'a');
        fwrite($file, "File Logger: [$level] $message\n");
        fclose($file);
    }
}

// You can add more concrete loggers as needed (e.g., DatabaseLogger, EmailLogger, etc.)

Implementation

Now, you can use these loggers in your application:

// Create logger instances
$consoleLogger = new ConsoleLogger();
$fileLogger = new FileLogger();

// Set up the chain of responsibility
$consoleLogger->setNext($fileLogger);

// Log messages
$consoleLogger->logMessage('INFO', 'This is an information message.');
$consoleLogger->logMessage('ERROR', 'This is an error message.');

This setup allows you to add or remove loggers from the chain easily and customize the behavior of each logger separately. Adjust the write method in each concrete logger to suit your specific logging needs, whether it’s writing to a file, database, sending emails, or other actions you require for logging.

Leave a Reply