Skip to content

Instantly share code, notes, and snippets.

@theMackabu
Last active February 10, 2023 20:12
Show Gist options
  • Save theMackabu/141c953b182cc91052d42030da16750e to your computer and use it in GitHub Desktop.
Save theMackabu/141c953b182cc91052d42030da16750e to your computer and use it in GitHub Desktop.
Simple java logger example
// minified
class Log{public static final String RESET="\u001B[0m";public static final String RED="\u001B[31m";public static final String CYAN="\u001B[36m";static void p(Boolean ln,Boolean err,Object... args){java.io.Console console=java.lang.System.console();for(Object pts:args)if(err)java.lang.System.err.print(pts);else console.writer().print(pts);if(ln)console.writer().println();}static String f(Object format,Object... args){return new java.util.Formatter(java.util.Locale.getDefault()).format(format.toString(),args).toString();}public static void print(Object message,Object... args){p(false,false,f(message,args));}public static void println(Object message,Object... args){p(true,false,f(message,args));}public static void info(Object message,Object... args){p(true,false,f(CYAN+message+RESET,args));}public static void error(Object message,Object... args){p(true,true,f(RED+message+RESET,args));}}
class ANSI {
public static final String RESET = "\u001B[0m";
public static final String BLACK = "\u001B[30m";
public static final String RED = "\u001B[31m";
public static final String GREEN = "\u001B[32m";
public static final String YELLOW = "\u001B[33m";
public static final String BLUE = "\u001B[34m";
public static final String PURPLE = "\u001B[35m";
public static final String CYAN = "\u001B[36m";
public static final String WHITE = "\u001B[37m";
}
class Log {
static void p(Boolean ln, Boolean err, Object... args) {
java.io.Console console = java.lang.System.console();
for (Object pts : args)
if (err) java.lang.System.err.print(pts);
else console.writer().print(pts);
if (ln) console.writer().println();
}
static String f(Object format, Object... args) {
return new java.util.Formatter(java.util.Locale.getDefault())
.format(format.toString(), args)
.toString();
}
public static void print(Object message, Object... args) {
p(false, false, f(message, args));
}
public static void println(Object message, Object... args) {
p(true, false, f(message, args));
}
public static void info(Object message, Object... args) {
p(true, false, f(ANSI.CYAN + message + ANSI.RESET, args));
}
public static void error(Object message, Object... args) {
p(true, true, f(ANSI.RED + message + ANSI.RESET, args));
}
}
public class Main {
public static void main(String[] args) {
String str = "world";
int num = 10;
Log.println("hello %s (%d)", str, num);
Log.info("hello %s (%d)", str, num);
Log.error("hello %s (%d)", str, num);
Log.print("\n");
Log.println(System.getProperties());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment