0

I am trying to add logging to an application for collaborating such that the user's actions (like chat messages and UI clicks) are logged to a local text file. Later I will synchronize the log text files from different users (using different computers) with the goal of having the logs in chronological order by timestamp. I am wondering how I should record the timestamp to avoid relying on the system clock since that will likely cause inaccurate syncing of the log files.

I am currently using the java Instant class (import java.time.Instant;), but I am not sure if this is the way to go.

String timestamp = Instant.now().toString();
try {
      BufferedWriter writer = new BufferedWriter(new FileWriter("actionLogs.txt", true));
      writer.write("\n" + timestamp + "\t" + username + "\t" + chatContents);
      writer.close();
} catch (IOException ex) {
      System.out.println("caught an IOException");
      ex.printStackTrace(System.out);
}

Thanks for your suggestions!

KimY
  • 33
  • 4
  • Instant is a good starting point. Prefer toEpochMilli() over toString() https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#toEpochMilli-- – Not a JD Mar 28 '19 at 19:41
  • get your time from an itp server https://stackoverflow.com/questions/4442192/how-to-use-an-internet-time-server-to-get-the-time – squishy Mar 28 '19 at 20:26

2 Answers2

0

An instant is a certain point in time; that implies it's not bound to any local system clock. The Instant class is pretty much the way to go.

It is often represented in UTC, the universal coordinated time. UTC is designed to be the same for all observers.

Of course, the system timer is used as source of the time, so strictly speaking, it depends on the system clock on the local machine, unless you get the time from a time server, but for logging, I would not recommend that.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
0

Well, bind it to specific timezone and turn it to timemillis, something like:

 String text = String.valueOf(LocalDateTime.now().atZone(ZoneOffset.UTC).toInstant().toEpochMilli());
 System.out.println(text);
MS90
  • 1,219
  • 1
  • 8
  • 17