Java Design Program · CD15
Design a Logger with Log Levels in Java
Debug messages help during development but flood production logs. A logger with levels writes only what is important enough for the current setting.
Problem Statement
Design a Logger with the levels DEBUG, INFO, WARN and ERROR, a minimum level, and one or more outputs such as the console and a file.
A message is written to every output only if its level is at or above the minimum, and the level can be changed while the program runs.
Input/Output Examples
minimum WARN; log INFO and ERROROutputonly the ERROR lineExplanation: INFO is below WARN.an ERROR messageOutputconsole and file both get itExplanation: every output receives each written line.setLevel(DEBUG), log DEBUGOutputthe DEBUG line is writtenExplanation: the new minimum applies at once.Visual Explanation
- LevelsorderDEBUGINFOWARNERRORminimum = WARN
- info(...)INFO < WARNdropreturn early not written
- error(...)ERROR ≥ WARNwriteconsole + file written
- Doneonly important lines
Each output is a strategy: the logger does not know whether a line goes to the console, a file or a network service.
Approaches
Both approaches filter by level the same way. The first sends a line to a list of outputs; the second passes it along a chain of handlers.
Approach 1: Enum Levels and Output List (Recommended)
Idea: declare the levels in severity order and drop a message when level.compareTo(minLevel) < 0; otherwise give the line to each output.
- Declare
enum Level { DEBUG, INFO, WARN, ERROR }. - Store the minimum level in a
volatilefield so changes are visible to all threads. - Return early for lower levels.
- Format the line once and send it to each
Consumer<String>output.
Time: O(o) · Space: O(o). o is the number of outputs; a dropped message costs O(1).
Approach 2: Chain of Responsibility
Idea: link the outputs into a chain of handlers; each writes the line and passes it to the next one.
- Build the handlers back to front so each points to the next.
- Filter by level in the logger.
- Call the first handler, which forwards the line along the chain.
Time: O(o) · Space: O(o).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Enum Levels and Output List (Recommended)
Short, clear and easy to add outputs to.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class LoggerEnum {
// The enum order is the severity order, so "is this enabled?" is one compareTo()
enum Level { DEBUG, INFO, WARN, ERROR }
static class Logger {
private volatile Level minLevel;
private final List<Consumer<String>> outputs; // each output is a strategy for writing a line
Logger(Level minLevel, List<Consumer<String>> outputs) {
this.minLevel = minLevel;
this.outputs = List.copyOf(outputs);
}
void setLevel(Level level) { this.minLevel = level; }
void log(Level level, String message) {
if (level.compareTo(minLevel) < 0) {
return; // filtered before any formatting work
}
String line = "[" + level + "] " + message;
outputs.forEach(out -> out.accept(line));
}
void debug(String m) { log(Level.DEBUG, m); }
void info(String m) { log(Level.INFO, m); }
void warn(String m) { log(Level.WARN, m); }
void error(String m) { log(Level.ERROR, m); }
}
public static void main(String[] args) {
List<String> file = new ArrayList<>();
Logger log = new Logger(Level.WARN, List.of(
line -> System.out.println("console | " + line),
line -> file.add(line)));
log.info("user 7 signed in"); // below WARN: dropped
log.error("payment gateway timed out");
log.debug("cache size = 120"); // below WARN: dropped
log.warn("disk 85% full");
log.setLevel(Level.DEBUG);
log.debug("retrying payment");
System.out.println("file has " + file.size() + " lines, first: " + file.get(0));
}
}
console | [ERROR] payment gateway timed out console | [WARN] disk 85% full console | [DEBUG] retrying payment file has 3 lines, first: [ERROR] payment gateway timed out
Time complexity: O(o) · Space complexity: O(o).
Approach 2: Chain of Responsibility
Useful when handlers need their own rules, such as a file handler that keeps only errors.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class LoggerChain {
enum Level { DEBUG, INFO, WARN, ERROR }
// Chain of responsibility: each handler has its own minimum level and passes the line on
static class Handler {
private final Consumer<String> output;
private final Handler next;
Handler(Consumer<String> output, Handler next) {
this.output = output;
this.next = next;
}
void handle(String line) {
output.accept(line);
if (next != null) next.handle(line);
}
}
static class Logger {
private volatile Level minLevel;
private final Handler chain;
Logger(Level minLevel, List<Consumer<String>> outputs) {
this.minLevel = minLevel;
Handler h = null;
for (int i = outputs.size() - 1; i >= 0; i--) {
h = new Handler(outputs.get(i), h); // build the chain back to front
}
this.chain = h;
}
void setLevel(Level level) { this.minLevel = level; }
void log(Level level, String message) {
if (level.ordinal() >= minLevel.ordinal() && chain != null) {
chain.handle("[" + level + "] " + message);
}
}
void debug(String m) { log(Level.DEBUG, m); }
void info(String m) { log(Level.INFO, m); }
void warn(String m) { log(Level.WARN, m); }
void error(String m) { log(Level.ERROR, m); }
}
public static void main(String[] args) {
List<String> file = new ArrayList<>();
Logger log = new Logger(Level.WARN, List.of(
line -> System.out.println("console | " + line),
line -> file.add(line)));
log.info("user 7 signed in"); // below WARN: dropped
log.error("payment gateway timed out");
log.debug("cache size = 120"); // below WARN: dropped
log.warn("disk 85% full");
log.setLevel(Level.DEBUG);
log.debug("retrying payment");
System.out.println("file has " + file.size() + " lines, first: " + file.get(0));
}
}
console | [ERROR] payment gateway timed out console | [WARN] disk 85% full console | [DEBUG] retrying payment file has 3 lines, first: [ERROR] payment gateway timed out
Time complexity: O(o) · Space complexity: O(o).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Enum Levels and Output List | O(o) | O(o) |
| Chain of Responsibility | O(o) | O(o) |
A filtered message costs one comparison. A written message is formatted once and passed to each of the o outputs.
Interview Tips and Recommended Approach
- Filter before formatting. Building the string for a message that is dropped wastes time.
- Use a
Supplier<String>for expensive messages so they are built only when needed. - Mention thread safety of the outputs; a shared file writer needs synchronisation or a queue.
- Know SLF4J and Logback. In real projects, use a logging library rather than writing one.
Recommended Approach: Enum Levels and Output List
Why: the enum gives an ordered set of levels for free, and a list of outputs is the simplest way to support several destinations.