The following code creates a directory with name as current date and stores the log files in that directory. But next the log files of the next days keep are also stored in same directory. I want create a new directory every day having the same name as current date and store new log file in it.
private static Date dir1 = new java.util.Date(System.currentTimeMillis());
private static Date dir = new java.util.Date(System.currentTimeMillis());
private static String baseDir1 = "/home/gaurav/flinklogs/";
private static String newDir1 = createDateBasedDirectory(baseDir1, dir1);
private static FileHandler fh1;
static {
try {
fh1 = new FileHandler(newDir1 + "/data.log", 0, 1, true);
} catch (IOException | SecurityException e) {
}
}
public static void main(String args[]) throws Exception {
Logger logger = Logger.getLogger("MyLog");
// This block configure the logger with handler and formatter
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info(e.getMessage());
}
public static String createDateBasedDirectory(String baseDirectory, Date argDate) {
String newDir = null;
if (baseDirectory != null && argDate != null) {
try {
String format = "yyyy-MM-dd";
DateFormat dateFormatter = new SimpleDateFormat(format);
String date = dateFormatter.format(argDate);
// check if the directory exists:
String todaysLogDir = baseDirectory + "\\" + date;
Path todaysDirectoryPath = Paths.get(todaysLogDir);
// and check if this Path exists
if (Files.exists(todaysDirectoryPath)) {
// if present, just return it in order to write (into) a log file there
return todaysDirectoryPath.toUri().toString();
} else {
newDir = baseDirectory + date;
new File(newDir).mkdir();
return newDir.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return newDir;
}