Creates multiple log files
Hi! I am having a problem. I want to write all the stackTraces to my log file. So I have created a java file to write log...
import java.util.Properties;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class WriteToLog {
private static final String root = System.getProperty("user.dir");
private static final String log_file = "//MyLogFile.log";
private static Logger logger = Logger.getLogger("MyLog");
private static Properties prop;
private static FileHandler fh;
public static void writeLog(String location, String message) {
try {
fh = new FileHandler((new StringBuilder()).append(root).append(log_file).toS tring(), true);
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.info(location + message);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
and when I write to log file using
catch (SQLException e)
{
WriteToLog.writeLog(connectMySql.class.getSimpleNa me(), "Sql Connection failed");
}
like this. It writes but creates lots of log files. How Can I append all these logs to single logfile?
Re: Creates multiple log files
Add the FileHandler a single time, not every time you try to write out to the log.
Re: Creates multiple log files
I tried to add the file handler on constructor in this way :
public WriteToLog()
{
try
{
fh = new FileHandler((new StringBuilder()).append(ruta).append(log_file).toS tring(), true);
logger.addHandler(fh);
}
catch (Exception e)
{
e.printStackTrace();
}
}
it gives me the null pointer exception.
Re: Creates multiple log files
I got it.
I just needed to add to methods to filehandler.
fh.flush();
fh.close();