-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLogger.java
More file actions
76 lines (71 loc) · 3.3 KB
/
Logger.java
File metadata and controls
76 lines (71 loc) · 3.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Logger {
private String peerId;
private String logFileName;
private FileOutputStream logFileStream;
private OutputStreamWriter out;
public Logger(String peerId) {
this.peerId = peerId;
this.logFileName = "log_peer_" + peerId + ".log";
}
public void start() throws FileNotFoundException {
this.logFileStream = new FileOutputStream(this.logFileName, false);
this.out = new OutputStreamWriter(this.logFileStream); // default encoding - UTF-8
}
public void stop() throws IOException {
out.flush();
logFileStream.close();
}
public void writeLog(LogMessage logMessage, String[] args) {
// args is always array of strings; their structure based on log message is mentioned in LogMessage.java
String text = null;
String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"));
try {
switch (logMessage) {
case CLIENT_CONNECT:
text = "Peer " + this.peerId + " makes a connection to Peer " + args[0] + ".";
break;
case SERVER_CONNECT:
text = "Peer " + this.peerId + " is connected from Peer " + args[0] + ".";
break;
case CHANGE_PREFERRED_NEIGHBOURS:
text = "Peer " + this.peerId + " has the preferred neighbors " + String.join(", ", args) + ".";
break;
case CHANGE_OPTIMISTIC_NEIGHBOUR:
text = "Peer "+ this.peerId + " has the optimistically unchoked neighbor " + args[0];
break;
case UNCHOKING:
text = "Peer " + this.peerId + " is unchoked by " + args[0] + ".";
break;
case CHOKING:
text = "Peer " + this.peerId + " is choked by " + args[0] + ".";
break;
case RECEIVE_HAVE:
text = "Peer " + this.peerId + " received the 'have' message from " + args[0] + " for the piece " + args[1] + ".";
break;
case RECEIVE_INTERESTED:
text = "Peer " + this.peerId + " received the 'interested' message from " + args[0] + ".";
break;
case RECEIVE_NOT_INTERESTED:
text = "Peer " + this.peerId + " received the 'not interested' message from " + args[0] + ".";
break;
case PIECE_DOWNLOAD:
text = "Peer " + this.peerId + " has downloaded the piece " + args[1] + " from " + args[0] + ". Now the number of pieces it has is " + args[2] + ".";
break;
case DOWNLOAD_COMPLETE:
text = "Peer " + this.peerId + " has downloaded the complete file.";
break;
default:
throw new Exception("Invalid Log Message");
}
out.write(dateTime + ": " + text + "\n");
} catch (Exception ex) {
// ex.printStackTrace();
}
}
}