Monday, June 24, 2019

java - how to store log files in directory (directory name having current date) every day

Following code create a directory with name as current date and store the log files in that directory, but next day the log files keep store data in same directory...i want create new directory every day which having 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;
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...