In this article, we will explore the design and development of a Logging Framework in Java, using object-oriented programming principles.
A Logging Framework is crucial for effective monitoring, debugging, and auditing of applications.
The Logging Framework should:
- Support Multiple Log Levels: Including INFO, DEBUG, WARN, and ERROR.
- Flexible Log Destination: Enable logging to various outputs like the console, files, or external services.
- Configurable Formatting: Allow for custom log message formats.
- Performance Efficiency: Ensure minimal impact on application performance.
- Logging Messages: Ability to log messages at different levels.
- Configuring Loggers: Setup loggers with varying settings and outputs.
- Managing Log Output: Direct messages to appropriate destinations based on configurations.
Logger
: Main interface for logging messages.LogLevel
: Enum representing log levels.LogDestination
: Interface for different log output destinations.ConsoleDestination
,FileDestination
: Implementations of theLogDestination
interface.
Defines different levels of logging.
public enum LogLevel {
INFO, DEBUG, WARN, ERROR
}
Interface for different log destinations.
public interface LogDestination {
void writeLog(String message);
}
Implementation for logging to the console.
public class ConsoleDestination implements LogDestination {
@Override
public void writeLog(String message) {
System.out.println(message);
}
}
Implementation for logging to a file.
import java.io.FileWriter;
import java.io.IOException;
public class FileDestination implements LogDestination {
private String filename;
public FileDestination(String filename) {
this.filename = filename;
}
@Override
public void writeLog(String message) {
try (FileWriter fileWriter = new FileWriter(filename, true)) {
fileWriter.write(message + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Main class for logging operations.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Logger {
private LogLevel level;
private LogDestination destination;
public Logger(LogLevel level, LogDestination destination) {
this.level = level;
this.destination = destination;
}
public void log(LogLevel level, String message) {
if (level.ordinal() >= this.level.ordinal()) {
String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String formattedMessage = timestamp + " [" + level.name() + "] " + message;
destination.writeLog(formattedMessage);
}
}
// Getters and setters...
}