Skip to content

Instantly share code, notes, and snippets.

@amiraliakbari
Created November 10, 2014 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amiraliakbari/d65d5c69f39ea83804fb to your computer and use it in GitHub Desktop.
Save amiraliakbari/d65d5c69f39ea83804fb to your computer and use it in GitHub Desktop.
Java Logger
package livedoc.utils;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Logger {
protected static Logger instance;
PrintWriter logFile;
DateFormat dateFormat;
long lastLogTime;
protected Logger (String logPath) {
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
logFile = new PrintWriter(new FileWriter(logPath + "/livedocLog.txt", true));
} catch (IOException e) {
logFile = null;
e.printStackTrace();
}
updateTime();
}
protected Logger () {
this(System.getProperty("user.home"));
}
protected void finalize() throws Throwable {
close();
}
public static Logger get() {
if (instance == null) {
instance = new Logger();
}
return instance;
}
private void updateTime() {
lastLogTime = System.currentTimeMillis();
}
public void log(String logger, String log, boolean doProfile) {
String str = dateFormat.format(new Date()).replace(' ', 'T') + " ";
if (!logger.isEmpty()) {
str += "[" + logger.toUpperCase() + "] ";
}
str += log;
if (logFile != null) {
logFile.write(str + "\n");
logFile.flush();
} else {
System.out.println(str);
}
if (doProfile) {
updateTime();
}
}
public void log(String logger, String log) {
log(logger, log, true);
}
public void log(String log) {
log("", log);
}
public void profile(String progress) {
long time = System.currentTimeMillis() - lastLogTime;
log("profile", progress + " (time: " + time + "ms)");
}
public void profile() {
long time = System.currentTimeMillis() - lastLogTime;
log("profile", "time: " + time + "ms");
}
public void logException(Exception e) {
log("error", e.getMessage());
}
public void close() {
logFile.close();
logFile = null;
}
}
Logger.get().log("ui", "Plugin initialized");
Logger.get().log("debug", "x=" + x);
Logger.get().log("debug", "start to do X");
//do X
Logger.get().profile(); // outputs time spent on X
Logger.get().log("debug", "start to do X,Y,Z");
//do X
Logger.get().profile("X"); // outputs time spent on X
//do Y
Logger.get().profile("Y"); // outputs time spent on Y
//do Z
Logger.get().profile("Z"); // outputs time spent on Z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment