/
SystemLogger.java
83 lines (68 loc) · 2.99 KB
/
SystemLogger.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package net.ME1312.Galaxi.Engine.Runtime;
import net.ME1312.Galaxi.Library.Util;
import net.ME1312.Galaxi.Log.LogStream;
import net.ME1312.Galaxi.Log.Logger;
import org.jline.reader.LineReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static java.nio.charset.StandardCharsets.UTF_8;
import static net.ME1312.Galaxi.Engine.GalaxiOption.COLOR_LOG_LEVELS;
final class SystemLogger extends OutputStream {
private final HashMap<String, LogStream> last = new HashMap<String, LogStream>();
private static ExecutorService service;
private static FileLogger file;
private final boolean error;
private SystemLogger(boolean level) {
this.error = level;
}
static void start(Console console) throws Exception {
Util.reflect(Logger.class.getDeclaredField("writer"), null, file = new FileLogger(new ConsoleLogger(console)));
Util.reflect(Logger.class.getDeclaredField("color"), null, COLOR_LOG_LEVELS.usr().equalsIgnoreCase("true") || (COLOR_LOG_LEVELS.usr().length() <= 0 && COLOR_LOG_LEVELS.app()));
Util.reflect(Logger.class.getDeclaredField("service"), null, service = Executors.newSingleThreadExecutor(r -> new Thread(r, Engine.getInstance().getEngineInfo().getName() + "::Log_Spooler")));
System.setOut(new PrintStream(new SystemLogger(false), false, UTF_8.name()));
System.setErr(new PrintStream(new SystemLogger(true), false, UTF_8.name()));
}
static File history() {
return file.history();
}
static void stop() throws Exception {
Thread.sleep(125);
Util.reflect(Logger.class.getDeclaredField("service"), null, null);
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
file.close();
Console console = Engine.getInstance().getCommandProcessor();
if (console.jstatus) {
console.jline.callWidget(LineReader.CLEAR);
console.jline.getTerminal().flush();
}
}
private String origin() {
int i = 0;
String origin = java.lang.System.class.getCanonicalName();
for (StackTraceElement element : new Exception().getStackTrace()) {
if (i > 1 && Engine.getInstance().code.knownClasses.containsKey(element.getClassName())) {
origin = element.getClassName().replaceAll("\\$([^.$\\d]+)", ".$1").replaceAll("\\$[\\d]+", "");
break;
}
i++;
}
return origin;
}
@Override
public synchronized void write(int c) throws IOException {
String origin = origin();
if (!last.containsKey(origin)) {
Logger log = new Logger(origin);
last.put(origin, (error)?log.error:log.info);
}
LogStream log = last.get(origin);
log.toPrimitive().write(c);
}
}