Better console / Better logging

This commit is contained in:
Anuken 2019-12-08 15:17:14 -05:00
parent 803719b216
commit 9f29898713
11 changed files with 71 additions and 131 deletions

View File

@ -32,8 +32,8 @@ public abstract class ClientLauncher extends ApplicationCore implements Platform
@Override
public void setup(){
Vars.loadLogger();
Vars.platform = this;
Log.setUseColors(false);
beginTime = Time.millis();
Time.setDeltaProvider(() -> {

View File

@ -15,6 +15,7 @@ import io.anuke.mindustry.entities.effect.*;
import io.anuke.mindustry.entities.traits.*;
import io.anuke.mindustry.entities.type.*;
import io.anuke.mindustry.game.*;
import io.anuke.mindustry.game.EventType.*;
import io.anuke.mindustry.gen.*;
import io.anuke.mindustry.input.*;
import io.anuke.mindustry.maps.*;
@ -25,12 +26,14 @@ import io.anuke.mindustry.world.blocks.defense.ForceProjector.*;
import java.nio.charset.*;
import java.util.*;
import static io.anuke.arc.Core.*;
import static io.anuke.arc.Core.settings;
@SuppressWarnings("unchecked")
public class Vars implements Loadable{
/** Whether to load locales.*/
public static boolean loadLocales = true;
/** Whether the logger is loaded. */
public static boolean loadedLogger = false;
/** Maximum schematic size.*/
public static final int maxSchematicSize = 32;
/** All schematic base64 starts with this string.*/
@ -270,6 +273,31 @@ public class Vars implements Loadable{
maps.load();
}
public static void loadLogger(){
if(loadedLogger) return;
String[] tags = {"[green][D][]", "[royal][I][]", "[yellow][W][]", "[scarlet][E][]", ""};
String[] stags = {"&lc&fb[D]", "&lg&fb[I]", "&ly&fb[W]", "&lr&fb[E]", ""};
Array<String> logBuffer = new Array<>();
Log.setLogger((level, text, args) -> {
String result = Log.format(text, args);
System.out.println(Log.format(stags[level.ordinal()] + "&fr " + text, args));
result = tags[level.ordinal()] + " " + result;
if(!headless && (ui == null || ui.scriptfrag == null)){
logBuffer.add(result);
}else if(!headless){
ui.scriptfrag.addMessage(result);
}
});
Events.on(ClientLoadEvent.class, e -> logBuffer.each(ui.scriptfrag::addMessage));
loadedLogger = true;
}
public static void loadSettings(){
Core.settings.setAppName(appName);

View File

@ -87,12 +87,12 @@ public class ContentLoader{
}
}
Log.info("--- CONTENT INFO ---");
Log.debug("--- CONTENT INFO ---");
for(int k = 0; k < contentMap.length; k++){
Log.info("[{0}]: loaded {1}", ContentType.values()[k].name(), contentMap[k].size);
Log.debug("[{0}]: loaded {1}", ContentType.values()[k].name(), contentMap[k].size);
}
Log.info("Total content loaded: {0}", Array.with(ContentType.values()).mapInt(c -> contentMap[c.ordinal()].size).sum());
Log.info("-------------------");
Log.debug("Total content loaded: {0}", Array.with(ContentType.values()).mapInt(c -> contentMap[c.ordinal()].size).sum());
Log.debug("-------------------");
}
/** Calls Content#init() on everything. Use only after all modules have been created.*/

View File

@ -483,7 +483,7 @@ public class ContentParser{
FieldMetadata metadata = fields.get(child.name().replace(" ", "_"));
if(metadata == null){
if(ignoreUnknownFields){
Log.err("{0}: Ignoring unknown field: " + child.name + " (" + type.getName() + ")", object);
Log.warn("{0}: Ignoring unknown field: " + child.name + " (" + type.getName() + ")", object);
continue;
}else{
SerializationException ex = new SerializationException("Field not found: " + child.name + " (" + type.getName() + ")");

View File

@ -101,7 +101,7 @@ public class Mods implements Loadable{
Array<FileHandle> overrides = mod.root.child("sprites-override").findAll(f -> f.extension().equals("png"));
packSprites(sprites, mod, true);
packSprites(overrides, mod, false);
Log.info("Packed {0} images for mod '{1}'.", sprites.size + overrides.size, mod.meta.name);
Log.debug("Packed {0} images for mod '{1}'.", sprites.size + overrides.size, mod.meta.name);
totalSprites += sprites.size + overrides.size;
}
@ -112,7 +112,7 @@ public class Mods implements Loadable{
}
}
Log.info("Time to pack textures: {0}", Time.elapsed());
Log.debug("Time to pack textures: {0}", Time.elapsed());
}
private void packSprites(Array<FileHandle> sprites, LoadedMod mod, boolean prefix){
@ -158,12 +158,12 @@ public class Mods implements Loadable{
Core.atlas = packer.flush(filter, new TextureAtlas());
Core.atlas.setErrorRegion("error");
Log.info("Total pages: {0}", Core.atlas.getTextures().size);
Log.debug("Total pages: {0}", Core.atlas.getTextures().size);
}
packer.dispose();
packer = null;
Log.info("Time to update textures: {0}", Time.elapsed());
Log.debug("Time to update textures: {0}", Time.elapsed());
}
private PageType getPage(AtlasRegion region){

View File

@ -1,20 +1,17 @@
package io.anuke.mindustry.mod;
import io.anuke.arc.*;
import io.anuke.arc.collection.*;
import io.anuke.arc.files.*;
import io.anuke.arc.util.*;
import io.anuke.arc.util.Log.*;
import io.anuke.mindustry.*;
import io.anuke.mindustry.mod.Mods.*;
import org.mozilla.javascript.*;
import static io.anuke.mindustry.Vars.*;
public class Scripts implements Disposable{
private final Context context;
private final String wrapper;
private Scriptable scope;
private Array<String> logBuffer = new Array<>();
public Scripts(){
Time.mark();
@ -50,18 +47,11 @@ public class Scripts implements Disposable{
}
public void log(String source, String message){
Log.info("[{0}]: {1}", source, message);
logBuffer.add("[accent][" + source + "]:[] " + message);
if(!headless && ui.scriptfrag != null){
onLoad();
}
log(LogLevel.info, source, message);
}
public void onLoad(){
if(!headless){
logBuffer.each(ui.scriptfrag::addMessage);
}
logBuffer.clear();
public void log(LogLevel level, String source, String message){
Log.log(level, "[{0}]: {1}", source, message);
}
public void run(LoadedMod mod, FileHandle file){
@ -72,7 +62,7 @@ public class Scripts implements Disposable{
try{
context.evaluateString(scope, script, file, 1, null);
}catch(Throwable t){
log(file, "[scarlet]" + getError(t));
log(LogLevel.err, file, "" + getError(t));
}
}

View File

@ -19,7 +19,7 @@ import static io.anuke.arc.Core.*;
import static io.anuke.mindustry.Vars.*;
public class ScriptConsoleFragment extends Table{
private final static int messagesShown = 14;
private final static int messagesShown = 30;
private Array<String> messages = new Array<>();
private boolean open = false, shown;
private TextField chatfield;
@ -71,16 +71,13 @@ public class ScriptConsoleFragment extends Table{
historyPos--;
updateChat();
}
scrollPos = (int)Mathf.clamp(scrollPos + input.axis(Binding.chat_scroll), 0, Math.max(0, messages.size - messagesShown));
}
scrollPos = (int)Mathf.clamp(scrollPos + input.axis(Binding.chat_scroll), 0, Math.max(0, messages.size - messagesShown));
});
history.insert(0, "");
setup();
if(mods.hasScripts()){
app.post(() -> mods.getScripts().onLoad());
}
}
public Fragment container(){

View File

@ -9,13 +9,8 @@ import io.anuke.arc.backends.sdl.jni.*;
import io.anuke.arc.collection.*;
import io.anuke.arc.files.*;
import io.anuke.arc.func.*;
import io.anuke.arc.input.*;
import io.anuke.arc.math.*;
import io.anuke.arc.scene.event.*;
import io.anuke.arc.scene.ui.*;
import io.anuke.arc.util.*;
import io.anuke.arc.util.Log.*;
import io.anuke.arc.util.io.*;
import io.anuke.arc.util.serialization.*;
import io.anuke.mindustry.*;
import io.anuke.mindustry.core.GameState.*;
@ -26,7 +21,6 @@ import io.anuke.mindustry.mod.Mods.*;
import io.anuke.mindustry.net.*;
import io.anuke.mindustry.net.Net.*;
import io.anuke.mindustry.type.*;
import io.anuke.mindustry.ui.*;
import java.io.*;
import java.net.*;
@ -49,6 +43,7 @@ public class DesktopLauncher extends ClientLauncher{
public static void main(String[] arg){
try{
Vars.loadLogger();
new SdlApplication(new DesktopLauncher(arg), new SdlConfig(){{
title = "Mindustry";
maximized = true;
@ -64,7 +59,6 @@ public class DesktopLauncher extends ClientLauncher{
}
public DesktopLauncher(String[] args){
Log.setUseColors(false);
Version.init();
boolean useSteam = Version.modifier.contains("steam");
testMobile = Array.with(args).contains("-testMobile");
@ -91,50 +85,7 @@ public class DesktopLauncher extends ClientLauncher{
}
}
StringBuilder base = new StringBuilder();
Log.setLogger(new LogHandler(){
@Override
public void print(String text, Object... args){
String out = Log.format(text, false, args);
base.append(out).append("\n");
}
});
Events.on(ClientLoadEvent.class, event -> {
Label[] label = {null};
boolean[] visible = {false};
Core.scene.table(t -> {
t.touchable(Touchable.disabled);
t.top().left();
t.update(() -> {
if(Core.input.keyTap(KeyCode.BACKTICK) && (loadError || System.getProperty("user.name").equals("anuke") || Version.modifier.contains("beta"))){
visible[0] = !visible[0];
}
t.toFront();
});
t.table(Styles.black3, f -> label[0] = f.add("").get()).visible(() -> visible[0]);
label[0].getText().append(base);
});
Log.setLogger(new LogHandler(){
@Override
public void print(String text, Object... args){
super.print(text, args);
String out = Log.format(text, false, args);
int maxlen = 2048;
if(label[0].getText().length() > maxlen){
label[0].setText(label[0].getText().substring(label[0].getText().length() - maxlen));
}
label[0].getText().append(out).append("\n");
label[0].invalidateHierarchy();
}
});
if(steamError != null){
Core.app.post(() -> Core.app.post(() -> Core.app.post(() -> {
ui.showErrorMessage(Core.bundle.format("steam.error", (steamError.getMessage() == null) ? steamError.getClass().getSimpleName() : steamError.getClass().getSimpleName() + ": " + steamError.getMessage()));
@ -176,19 +127,6 @@ public class DesktopLauncher extends ClientLauncher{
}
}
void fallbackSteam(){
try{
String name = "steam_api";
if(OS.isMac || OS.isLinux) name = "lib" + name;
if(OS.isWindows && OS.is64Bit) name += "64";
name += (OS.isLinux ? ".so" : OS.isMac ? ".dylib" : ".dll");
Streams.copyStream(getClass().getResourceAsStream(name), new FileOutputStream(name));
System.loadLibrary(new File(name).getAbsolutePath());
}catch(Throwable e){
logSteamError(e);
}
}
void initSteam(String[] args){
SVars.net = new SNet(new ArcNetImpl());
SVars.stats = new SStats();

View File

@ -1,3 +1,3 @@
org.gradle.daemon=true
org.gradle.jvmargs=-Xms256m -Xmx1024m
archash=6d310772fec1f69efeae2e487cab3bd64728ae05
archash=338ffafbb964ba9d41d89adc4ca4f1c589b46248

View File

@ -43,6 +43,9 @@ public class ServerControl implements ApplicationListener{
private static final int maxLogLength = 1024 * 512;
private static final int commandSocketPort = 6859;
protected static String[] tags = {"&lc&fb[D]", "&lg&fb[I]", "&ly&fb[W]", "&lr&fb[E]", ""};
protected static DateTimeFormatter dateTime = DateTimeFormatter.ofPattern("MM-dd-yyyy | HH:mm:ss");
private final CommandHandler handler = new CommandHandler("");
private final FileHandle logFolder = Core.settings.getDataDirectory().child("logs/");
@ -68,44 +71,19 @@ public class ServerControl implements ApplicationListener{
"globalrules", "{reactorExplosions: false}"
);
Log.setLogger(new LogHandler(){
DateTimeFormatter dateTime = DateTimeFormatter.ofPattern("MM-dd-yyyy | HH:mm:ss");
Log.setLogger((level, text, args1) -> {
String result = "[" + dateTime.format(LocalDateTime.now()) + "] " + format(tags[level.ordinal()] + " " + text + "&fr", args1);
System.out.println(result);
@Override
public void debug(String text, Object... args){
print("&lc&fb" + "[DEBG] " + text, args);
if(Core.settings.getBool("logging")){
logToFile("[" + dateTime.format(LocalDateTime.now()) + "] " + format(tags[level.ordinal()] + " " + text + "&fr", false, args1));
}
@Override
public void info(String text, Object... args){
print("&lg&fb" + "[INFO] " + text, args);
}
@Override
public void err(String text, Object... args){
print("&lr&fb" + "[ERR!] " + text, args);
}
@Override
public void warn(String text, Object... args){
print("&ly&fb" + "[WARN] " + text, args);
}
@Override
public void print(String text, Object... args){
String result = "[" + dateTime.format(LocalDateTime.now()) + "] " + format(text + "&fr", args);
System.out.println(result);
if(Core.settings.getBool("logging")){
logToFile("[" + dateTime.format(LocalDateTime.now()) + "] " + format(text + "&fr", false, args));
}
if(socketOutput != null){
try{
socketOutput.println(format(text + "&fr", false, args).replace("[DEBG] ", "").replace("[WARN] ", "").replace("[INFO] ", "").replace("[ERR!] ", ""));
}catch(Throwable e){
err("Error occurred logging to socket: {0}", e.getClass().getSimpleName());
}
if(socketOutput != null){
try{
socketOutput.println(format(text + "&fr", false, args1));
}catch(Throwable e){
err("Error occurred logging to socket: {0}", e.getClass().getSimpleName());
}
}
});

View File

@ -11,7 +11,11 @@ import io.anuke.mindustry.mod.*;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.net.*;
import java.time.*;
import static io.anuke.arc.util.Log.*;
import static io.anuke.mindustry.Vars.*;
import static io.anuke.mindustry.server.ServerControl.*;
public class ServerLauncher implements ApplicationListener{
static String[] args;
@ -21,6 +25,11 @@ public class ServerLauncher implements ApplicationListener{
ServerLauncher.args = args;
Vars.platform = new Platform(){};
Vars.net = new Net(platform.getNet());
Log.setLogger((level, text, args1) -> {
String result = "[" + dateTime.format(LocalDateTime.now()) + "] " + format(tags[level.ordinal()] + " " + text + "&fr", args1);
System.out.println(result);
});
new HeadlessApplication(new ServerLauncher(), null, throwable -> CrashSender.send(throwable, f -> {}));
}catch(Throwable t){
CrashSender.send(t, f -> {});