org.hwo.Logging neu

thobaben_serialize
Harald Wolff 2016-09-06 11:53:15 +02:00
parent 42db0d636f
commit 1a8e84ba90
2 changed files with 147 additions and 0 deletions

View File

@ -0,0 +1,9 @@
package org.hwo.logging;
public enum LogLevel {
INFO(1),WARN(3),ERROR(5),FATAL(10),DEBUG(25);
private final int n;
LogLevel(int l){ n=l; };
public int getLevel(){ return n; }
}

View File

@ -0,0 +1,138 @@
package org.hwo.logging;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.util.Date;
public class Logging {
private static Logging _inst;
private static PrintStream liveStream;
private PrintStream logStream;
private final DateFormat dateFormat;
public Logging(String filename){
dateFormat = DateFormat.getDateTimeInstance();
try {
File f = new File(filename);
File fold = new File(String.format("%s.old", filename));
if (fold.exists()){
fold.delete();
}
if (f.exists()){
f.renameTo(fold);
}
logStream = new PrintStream(filename);
} catch (FileNotFoundException e) {
liveStream.println("----!!!!! LOGGING ERROR !!!!!-----");
e.printStackTrace();
}
System.setErr(new PrintStream(new LoggingOutputStream(LogLevel.ERROR)));
System.setOut(new PrintStream(new LoggingOutputStream(LogLevel.INFO)));
}
private void _log(LogLevel logLevel,String message){
String formattedLine;
formattedLine = String.format("%s [%-8s] %s", dateFormat.format(new Date()),logLevel.toString(),message);
logStream.println(formattedLine);
logStream.flush();
if (liveStream != null){
liveStream.println(formattedLine);
liveStream.flush();
}
}
static public void setLogFileName(String logFileName){
_inst = new Logging(logFileName);
}
static public void log(LogLevel logLevel,String message){
if (_inst == null){
_inst = new Logging("application.log");
}
_inst._log(logLevel, message);
}
static public void log(String message){
log(LogLevel.INFO,message);
}
static public void log(LogLevel logLevel,String message,Object... args){
log(logLevel,String.format(message, args));
}
static public void log(String message,Object... args){
log(LogLevel.INFO,message,args);
}
static {
liveStream = System.out;
}
public class LoggingOutputStream extends OutputStream {
byte[] buffer;
int bufferPosition;
LogLevel
logLevel;
public LoggingOutputStream() {
buffer = new byte[4096];
bufferPosition = 0;
this.logLevel = LogLevel.INFO;
}
public LoggingOutputStream(LogLevel logLevel) {
buffer = new byte[4096];
bufferPosition = 0;
this.logLevel = logLevel;
}
@Override
public void flush(){
if (bufferPosition > 0){
_log(this.logLevel,new String(buffer,0,bufferPosition));
bufferPosition = 0;
};
}
@Override
public void write(int b) throws IOException {
if (b == 0x0A){
flush();
} else {
buffer[bufferPosition++] = new Integer(b).byteValue();
if (bufferPosition == buffer.length){
flush();
}
};
}
}
}