Implementing a logging mechanism using a Singleton class in Java

Category : Design Patterns | Sub Category : Questions on Design Patterns | By Prasad Bonam Last updated: 2023-07-12 02:29:23 Viewed : 322


Implementing a logging mechanism using a Singleton class in Java:

Here is an example of implementing a logging mechanism using a Singleton class in Java:

java
import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Logger { private static Logger instance; private PrintWriter writer; private Logger() { try { writer = new PrintWriter(new FileWriter("log.txt", true)); } catch (IOException e) { e.printStackTrace(); } } public static synchronized Logger getInstance() { if (instance == null) { instance = new Logger(); } return instance; } public void log(String message) { writer.println(message); writer.flush(); } public void close() { writer.close(); } }

In this example, the Logger class is implemented as a Singleton using a private constructor and a static getInstance() method.

The Logger class initializes a PrintWriter object in the constructor to write log messages to a file. The log file name is "log.txt" in this example, but you can modify it to suit your needs.

The log() method is used to write a log message to the log file. The close() method is used to close the writer when the logging is finished.

To use the Logger class, you can retrieve the singleton instance using Logger.getInstance() and then call the log() method to write log messages:

java
Logger logger = Logger.getInstance(); logger.log("Log message 1"); logger.log("Log message 2"); // ... logger.close(); // Close the logger when finished logging

Note that this is a simplified example to illustrate the Singleton pattern and logging mechanism. In a real-world scenario, you may need to handle log levels, log formatting, error handling, and other aspects specific to your logging requirements. Additionally, consider using established logging libraries such as Log4j or SLF4J for advanced logging features, configuration options, and better performance.


Search
Related Articles

Leave a Comment: