You are on page 1of 3

Simple logger bootstrap

import java.io.*;
import java.nio.charset.StandardCharsets;

public enum Logger implements ExceptionLogger {

instance("TEST");

private final String prefix;


public final Color warn_colour;
public final Color error_colour;
private final OutputStream output;
private final PrintStream print;

Logger(String prefix) {
this(prefix, Color.YELLOW, Color.RED);
}

Logger(String prefix, Color warn_colour, Color error_colour) {


this.prefix = String.format("[%s]", prefix);
this.warn_colour = warn_colour;
this.error_colour = error_colour;
this.output = new BufferedOutputStream(System.out);
this.print = new PrintStream(this.output);
}

private void write(Object object) {


String text;
if(object instanceof String)
text = (String) object;
else if(object instanceof Color)
text = object.toString();
else throw new RuntimeException("OBJECT IS NOT A TEXT: " + object);
try {
this.output.write(text.getBytes(StandardCharsets.UTF_8));
} catch (IOException ignored) {
System.out.print(text);
}
}

private void flush() {


try {
this.output.flush();
} catch (IOException ignored) {}
}
private String parsePrefix(String text) {
return this.prefix + " " + text + "\n";
}

public void info(String text) {


this.write(this.parsePrefix(text));
this.flush();
}

public void warn(String text) {


this.write(this.warn_colour + this.parsePrefix(text) + Color.RESET);
this.flush();
}

public void err(String text) {


this.write(this.error_colour + this.parsePrefix(text) + Color.RESET);
this.flush();
}

public void warn(Throwable e) {


this.write(this.warn_colour);
e.printStackTrace(this.print);
this.write(Color.RESET);
this.flush();
}

public void err(Throwable e) {


this.write(this.error_colour);
e.printStackTrace(this.print);
this.write(Color.RESET);
this.flush();
}

public void warn(String message, Throwable e) {


this.write(this.warn_colour);
this.write(message + "\n");
e.printStackTrace(this.print);
this.write(Color.RESET);
this.flush();
}

public void err(String message, Throwable e) {


this.write(this.error_colour);
this.write(message + "\n");
e.printStackTrace(this.print);
this.write(Color.RESET);
this.flush();
}

public PrintStream getPrintStream() {


return this.print;
}

@Override
public void lwjglError(LWJGLError e) {
this.err("LWJGL ERROR CAUGHT: ", e);
}

@Override
public void shaderError(ShaderError e) {
this.err("SHADER ERROR CAUGHT: ", e);
}

@Override
public void textureException(TextureException e) {
this.warn("INVALID TEXTURE: ", e);
}

@Override
public void exception(Throwable e) {
this.warn("OPENGL EXCEPTION CAUGHT: ", e);
}
}

You might also like