how does this look?
import java.util.*;
import java.text.*;
import java.io.*;
public class FileLogger extends SimpleLogger {
private File logFile;
private static FileLogger instance;
public static FileLogger getInstance(String logFilePath){
if (instance == null)
instance = new FileLogger(logFilePath);
return instance;
}
public FileLogger(String logFilePath){
logFile = new File(logFilePath);
try{
logFile.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void log(Level logLevel, String component, String msg)
throws LoggerException {
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
Date date = new Date();
if(logLevel.compareTo(getLevel()) >=0)
try{
FileWriter out = new FileWriter(logFile,true);
String dateTime = dateFormat.format(date);
BufferedWriter bufferedWriter = new BufferedWriter(out);
bufferedWriter.append("\n" + dateTime + logLevel + component + msg + "");
bufferedWriter.newLine();
bufferedWriter.close();
}catch (IOException e) {
throw new LoggerException();
}
}
@Override
public void log(Level error, String component, Throwable t)
throws LoggerException{
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
Date date = new Date();
if(error.compareTo(getLevel()) >=0)
try{
FileWriter out = new FileWriter(logFile,true);
String dateTime = dateFormat.format(date);
BufferedWriter bufferedWriter = new BufferedWriter(out);
bufferedWriter.append("\n" + dateTime + error + component + t + "");
bufferedWriter.newLine();
bufferedWriter.close();
}catch (IOException e) {
throw new LoggerException();
}
}
}
I am not 100% sure if it is meeting my requirements which are:
When a message is logged, the logfile should contain the following information: A timestamp The log level of the message The component that the program was in when the message is logged
The message itself, or the stack trace of the Throwable (in the case of the second log method
The logfile should always be appended to, so that log messages from successive invocations of the logged software all appear in the file. This allows developers to compare log messages over time.
Message is only logged if it is at the appropriate log level.