Design a Logger Class

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-04-01

Problem Statement

Design and implement a Logger class for applications that provides structured logging. The focus is on object-oriented design, modularity, extensibility, and thread-safety, allowing logs to be written to different outputs (console, file, external systems).


✅ Functional Requirements


1.Logging Levels
•Support standard log levels: DEBUG, INFO, WARN, ERROR, FATAL.
•Ability to set a minimum log level to filter messages.
2.Output Targets
•Console
•File (with optional rotation based on size or time)
•Optional: External systems (e.g., database, remote logging server)
3.Formatting
•Timestamps
•Log level
•Message
•Optional: Context information (e.g., thread ID, module name)
4.Configuration
•Set log level dynamically.
•Set output target(s).
•Optional: Enable asynchronous logging to avoid blocking.


🔐 Constraints & Assumptions


•Thread-safety: multiple threads may log concurrently.
•Efficient: minimal performance overhead.
•Supports singleton pattern if global logger instance is required.
•Language: C++ / Java / Python (conceptual design).


🧱 Key Components & Classes


1.Logger Class
1 2class Logger { 3private: 4 LogLevel level; 5 vector<LogTarget*> targets; // Console, File, etc. 6public: 7 static Logger& getInstance(); // Singleton 8 void log(LogLevel level, string message); 9 void debug(string message); 10 void info(string message); 11 void warn(string message); 12 void error(string message); 13 void fatal(string message); 14 void setLogLevel(LogLevel level); 15 void addTarget(LogTarget* target); 16};
1.LogTarget Interface (Abstract Class)
1 2class LogTarget { 3public: 4 virtual void write(string formattedMessage) = 0; 5};
1.Concrete Targets
1 2class ConsoleTarget : public LogTarget { ... }; 3class FileTarget : public LogTarget { ... }; 4class RemoteTarget : public LogTarget { ... }; // Optional
1.Formatter Class (Optional)
•Responsible for formatting log messages consistently.


🔄 Example Workflow


1.Initialize logger: Logger& logger = Logger::getInstance();
2.Set log level: logger.setLogLevel(INFO);
3.Add targets: logger.addTarget(new ConsoleTarget());
4.Log a message: logger.info("Application started"); → message is formatted and written to console.
5.Multiple threads can log simultaneously → thread-safety ensures no message interleaving.


🧪 Expected Deliverables


•Class diagram showing Logger, LogTarget interface, concrete targets, and optional Formatter.
•Implementation of logging methods (debug, info, warn, error, fatal) with filtering.
•Test cases:
•Logging to console and file
•Log level filtering
•Thread-safe logging simulation
•Optional: File rotation


💡 Discussion Points


•Trade-offs: synchronous vs asynchronous logging.
•Singleton vs multiple instances.
•Extensibility for new targets (e.g., network, database).
•Performance considerations: batching, buffering, or background writing.


Solution

Comments