Design Logger

  • It is based on Chain of Responsibility Pattern

Similar: Design ATM

  • Request: Rs. 2000
  • Handlers (Sequentially): `
[Rs. 2000 Handler] --> [Rs. 500 Handler] --> [Rs. 100 Handler]

Design Logger

  • We keep one abstract class (handler), here it is LogProcessor
public abstract class LogProcessor {
    public static int INFO = 1;
    public static int DEBUG = 2;
    public static int ERROR = 3;
 
    LogProcessor nextLogProcessor;
 
    LogProcessor(LogProcessor nextLogProcessor) {
        this.nextLogProcessor = nextLogProcessor;
    }
 
    public void log(int logLevel, String message) {
        if (this.nextLogProcessor != null) {
            nextLogProcessor.log(logLevel, message);
        }
    }
}
  • Concrete classes (Similarly DebugLogProcessor and ErrorLogProcessor)
public class InfoLogProcessor extends LogProcessor {
    InfoLogProcessor(LogProcessor nextLogProcessor) {
        super(nextLogProcessor);
    }
 
    public void log(int logLevel, String message) {
        if (logLevel == INFO) {
            System.out.println("INFO: " + message);
        } else {
            super.log(logLevel, message);
        }
    }
}

Driver

/**
 * log -----> [Info] --> [Debug] --> [Error]
 */
public static void main() {
    LogProcessor logObj = new InfoLogProcessor(new DebugLogProcessor(new ErrorLogProcessor(null)));
    logObj.log(LogProcessor.ERROR, "exception happens");
    logObj.log(LogProcessor.DEBUG, "need to debug this");
    logObj.log(LogProcessor.INFO, "just for info");
}