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:
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.