0%
Requirements
Define Core Objects
Analyze Relationships
Establish Hierarchy
LogLevel Enum
LogHandler Hierarchy
Design Patterns
Singleton: Global Logger Access
Strategy Pattern: Pluggable Handlers
Chain of Responsibility: Handler-Level Filtering
Define Class Members / Write Code
LogEntry (Immutable)
ConsoleHandler
FileHandler with Rotation
Logger (Singleton)
Run and Test
Adhere to SOLID Guidelines
Consider Scalability and Flexibility
Thread-Safe Logging
Asynchronous Logging for High Throughput
Runtime Configuration
Create/Explain Your Diagrams
Future Improvements
A logger seems like a utility class with a print statement. But a production logger must support multiple severity levels, route messages to multiple destinations simultaneously, format entries consistently, allow runtime configuration changes, and handle concurrent writes from dozens of threads without interleaving or losing entries. The design challenge is building a system where adding a new output destination requires zero changes to existing code.
Interview Dialogue
Functional Requirements
Non-Functional Requirements
A developer writes logger.info("User logged in", "AuthService"). What happens? The Logger checks whether INFO meets the current threshold. If it does, it creates a LogEntry, an immutable record capturing the timestamp, level, message, source class, and thread name right now, at the moment of the call. The Logger then iterates through its registered handlers. A ConsoleHandler prints the entry to stdout. A FileHandler writes it to a rotating log file. Each handler has its own level threshold: the console might show everything from DEBUG up, while the file records only ERROR and above. The handlers are all LogHandler subclasses. The Logger itself is a Singleton. One shared instance ensures all application classes use the same configuration. The LogLevel enum (DEBUG through FATAL) provides type-safe severity comparison. Not every noun becomes a class. "Threshold" is a field on Logger rather than its own entity, but nouns still give you a strong starting lineup.
The logger needs to create a LogEntry: an immutable record carrying the timestamp, log level, message, source class, and thread name. LogEntry is immutable because once created, a log record should never change. Modifying a log entry after creation would undermine the audit trail.
The logger itself is the Logger: a singleton that receives log calls, filters by level, and dispatches to handlers. Singleton because all application classes should share the same logger configuration and handler list.
Why Singleton? If each class created its own Logger, configuration would be scattered. Changing the log level would require updating every instance. A single shared Logger ensures one configuration point.
A LogLevel enum (DEBUG, INFO, WARN, ERROR, FATAL) with numeric priorities enables threshold comparison. DEBUG(0) is the lowest priority; FATAL(4) is the highest. A message is logged only if its level priority is at or above the threshold.
Each output destination is a LogHandler: an abstract class with a handle(LogEntry) method. Concrete handlers include ConsoleHandler (writes to stdout/stderr) and FileHandler (writes to a file with rotation). Handlers can have their own level thresholds for fine-grained control.
Why an enum for LogLevel instead of string constants? Strings compile fine but allow typos that fail silently at runtime. An enum constrains values at compile time, so the compiler catches invalid values before the code ever runs.
Aggregation: Logger has LogHandlers
Logger holds a list of LogHandler references. Handlers can exist independently: a ConsoleHandler could be shared across multiple Logger instances in a testing framework, or a FileHandler could be created and configured before being registered with the Logger. Removing a handler from the Logger does not destroy the handler.
Composition: Logger creates LogEntry
When Logger.log() is called, it creates a new LogEntry with the current timestamp, thread name, and message. The LogEntry exists only because of this log call. If the Logger discards it (below threshold), the entry is garbage collected. The LogEntry has no independent lifecycle.
Inheritance: ConsoleHandler and FileHandler extend LogHandler
Both concrete handlers inherit the level-filtering logic from LogHandler and implement doHandle() for their specific destination. This is inheritance with a template method: the abstract class provides the algorithm skeleton (check level, then write), and subclasses fill in the writing step.
Why not let each class instantiate its own Logger? Because configuration would be scattered across every instance. Changing the log level from INFO to DEBUG would require finding and updating every Logger. A shared Singleton ensures one configuration point: set the threshold once, and every log call across the entire application respects it.
Singleton: Logger.getInstance()
The static getInstance() method controls Logger creation. The relationship is between the Logger class and its single instance. Double-checked locking with a volatile field ensures exactly one instance is created even under concurrent access.
With the core objects and relationships established, the natural question is: how do we structure the hierarchy so that adding a new handler never breaks existing ones?
The isAtLeast() method encapsulates the comparison logic. Callers write level.isAtLeast(LogLevel.WARN) instead of comparing raw integers, making the intent clear.
The handle() method is a Template Method: it performs the level check (shared logic) and then calls doHandle() (subclass-specific logic). Subclasses only implement the writing step, never the filtering step.
Why is handle() not abstract? Because the level-filtering logic is identical for every handler. Making handle() concrete and final (or effectively final) prevents subclasses from accidentally skipping the level check. Only the writing logic varies.
Why not use an interface with a default handle() method instead of an abstract class? Because an interface default method can be overridden by any implementor, meaning a hasty DatabaseHandler could replace the level-filtering logic entirely. An abstract class with a concrete handle() calling an abstract doHandle() makes the filtering step mandatory and non-bypassable.
ConsoleHandler directs ERROR and FATAL to stderr, everything else to stdout. FileHandler writes to a buffered file with size-based rotation. Each handler manages its own I/O concerns independently.
The Logger uses the Singleton pattern so all application classes share one instance. Without it, each class would instantiate its own Logger, leading to scattered configuration and inconsistent behavior.
Double-checked locking with a volatile instance field ensures exactly one Logger is created even when multiple threads call getInstance() during application startup:
The outer null check avoids lock acquisition on every call (fast path). The inner null check prevents double creation if two threads pass the outer check simultaneously.
Each LogHandler is an interchangeable strategy for output. Logger dispatches to all registered handlers without knowing their implementation. Adding a SlackHandler or CloudWatchHandler requires implementing one class and calling logger.addHandler().
Each handler has its own level threshold, forming a filtering chain. ConsoleHandler might accept all levels (DEBUG and above) while FileHandler only logs ERROR and above. The same LogEntry passes through all handlers, and each independently decides whether to process it.
The Strategy pattern is the core extensibility mechanism. Adding a new log destination (Slack, database, cloud) requires one new LogHandler subclass. Logger, LogEntry, LogLevel, and all existing handlers remain untouched.
Why not use a single handler class with a destination enum and switch? Because ConsoleHandler routes errors to stderr, FileHandler manages rotation and buffered I/O, and a SlackHandler would need HTTP client configuration. These are completely unrelated I/O concerns. A switch statement would mix stdout writes, file rotation logic, and HTTP calls in one class, and every new destination would modify that switch.
When coding this live, start with immutable LogEntry and one concrete handler before the Logger singleton. That shows the data contract and the extension point first, then makes Logger feel like a dispatcher over stable abstractions instead of a god object.
All fields are final. The timestamp and thread name are captured at construction time, ensuring they reflect the moment the log call was made, not when the entry is eventually written (important for asynchronous logging). With the data record defined, the natural question is: where does it go?
ConsoleHandler is the simplest destination: it routes ERROR and FATAL to stderr and everything else to stdout. The next handler adds file-based persistence with rotation.
FileHandler uses its own writeLock to synchronize file writes and rotation. This provides defense-in-depth: even if the Logger-level lock is relaxed for async logging, individual handlers remain thread-safe. Finally, the Logger singleton ties the system together.
The logLevel field is volatile so changes by one thread are immediately visible to all other threads without requiring a lock.
Browse the complete solution code and run it. Try modifying the code to experiment with the design.
Single Responsibility Principle
Open/Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
In interviews, demonstrate OCP by saying: 'Our logger has been in production for two years. We have added Slack, CloudWatch, and Kafka handlers. The Logger class has not changed once since initial deployment.'
The Logger uses a ReentrantLock in log() to serialize dispatch. Each LogEntry is fully dispatched to all handlers before the next entry begins. FileHandler adds a second lock for file I/O, providing defense-in-depth.
The interleaving problem, step by step. Without the Logger-level lock, two threads logging simultaneously could produce garbled output:
With the lock, step 1 through all handlers completes before step 2 begins. Both console and file see entries in the same order.
For applications generating thousands of log entries per second, synchronous logging blocks the calling thread during I/O. An asynchronous enhancement adds a BlockingQueue between log() and the handlers:
Asynchronous logging removes the caller from the I/O path, but it does not remove capacity limits. If the writer thread cannot keep up, an unbounded queue quietly turns a latency problem into a memory problem. Real logger designs need a bounded queue and a clear drop-or-block policy.
The calling thread returns immediately after enqueueing. A single background thread dequeues and dispatches. This decouples caller latency from I/O latency entirely.
The logLevel field is volatile, so changes by one thread are visible to all others immediately. Calling setLogLevel(LogLevel.DEBUG) during a debugging session takes effect on the very next log call from any thread, without restart.
Junior: explain why the Logger needs a lock for dispatch.
Mid-level: design the async logging enhancement with a BlockingQueue.
Senior: discuss back-pressure when the queue fills, log loss policies (drop oldest, block caller, drop current), and monitoring queue depth as a health metric.
Why fine-grained locking instead of a single global lock? A global lock serializes all operations - only one thread can do anything at a time. Per-resource locks let operations on different resources proceed in parallel, scaling throughput linearly with the number of independent resources.
Below is the class diagram for the logger system.
Key points to highlight in an interview:
Log Aggregation and Monitoring
Add handlers for remote log aggregation services (ELK stack, Splunk, CloudWatch). Structured JSON formatting enables searchability, dashboards, and automated alerting on error patterns. Each service is one new LogHandler subclass.
Log File Rotation and Archival
Rotate log files by size or date. Archive old files with compression (gzip). Delete archives beyond a configurable retention period to manage disk usage automatically. The FileHandler already supports size-based rotation; adding date-based rotation is a straightforward enhancement.
Contextual Logging with MDC
Thread-local Mapped Diagnostic Context (MDC) maps carry request ID, user ID, and session ID. Every log entry from a thread automatically includes these values. This enables tracing a single request across multiple log lines and services without passing IDs explicitly through every method signature.
Structured Logging
Replace the format() method with a pluggable Formatter strategy. A JSONFormatter outputs entries as JSON objects for machine parsing. An XMLFormatter outputs XML for legacy systems. A PlainTextFormatter provides human-readable output. The Formatter is set per handler, allowing different formats for different destinations.
Sampling and Rate Limiting
In high-throughput systems, DEBUG logging can generate millions of entries per minute. A SamplingHandler wraps another handler and only passes through every Nth entry or a random percentage. This reduces volume while still providing statistical visibility.
Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.
0%
Requirements
Define Core Objects
Analyze Relationships
Establish Hierarchy
LogLevel Enum
LogHandler Hierarchy
Design Patterns
Singleton: Global Logger Access
Strategy Pattern: Pluggable Handlers
Chain of Responsibility: Handler-Level Filtering
Define Class Members / Write Code
LogEntry (Immutable)
ConsoleHandler
FileHandler with Rotation
Logger (Singleton)
Run and Test
Adhere to SOLID Guidelines
Consider Scalability and Flexibility
Thread-Safe Logging
Asynchronous Logging for High Throughput
Runtime Configuration
Create/Explain Your Diagrams
Future Improvements