-
Notifications
You must be signed in to change notification settings - Fork 0
/
Logger.java
52 lines (40 loc) · 1.46 KB
/
Logger.java
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
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
public abstract class Logger {
public enum LoggingType {
NO_LOG, // no log at all
ON_TERMINAL_ONLY, // log to System.out only
ON_FILE_ONLY, // log to file only
ON_FILE_AND_TERMINAL // log to both System.out and file
}
protected final LoggingType loggingType;
protected PrintStream ps;
protected Logger(LoggingType loggingType) {
this.loggingType = loggingType;
}
protected abstract String getLogFileSuffix();
protected synchronized PrintStream getPrintStream() throws IOException {
if (ps == null)
ps = new PrintStream(getLogFileSuffix() + "_" + System.currentTimeMillis() + ".log");
return ps;
}
protected boolean logToFile() {
return loggingType == LoggingType.ON_FILE_ONLY || loggingType == LoggingType.ON_FILE_AND_TERMINAL;
}
protected boolean logToTerminal() {
return loggingType == LoggingType.ON_TERMINAL_ONLY || loggingType == LoggingType.ON_FILE_AND_TERMINAL;
}
protected void log(String message) {
if (logToFile())
try { getPrintStream().println(message); } catch(Exception e) { e.printStackTrace(); }
if (logToTerminal())
System.out.println(message);
}
public void messageSent(Socket socket, String message) {
log("[" + socket.getLocalPort() + "->" + socket.getPort() + "] " + message);
}
public void messageReceived(Socket socket, String message) {
log("[" + socket.getLocalPort() + "<-" + socket.getPort() + "] " + message);
}
}