Last active
December 30, 2021 09:45
-
-
Save mrorigo/9163c6310945ecec1c175d9956744b03 to your computer and use it in GitHub Desktop.
Log4Simple
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.LinkedList; | |
import java.nio.charset.Charset; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.io.FileOutputStream; | |
public class Log4Simple | |
{ | |
public enum Level { | |
TRACE(0), | |
DEBUG(1), | |
INFO(2), | |
WARN(3), | |
ERROR(4), | |
FATAL(5); | |
private int value; | |
private Level(int value) { | |
this.value = value; | |
} | |
public int getValue() { | |
return this.value; | |
} | |
} | |
public abstract class Appender { | |
abstract void append(Level level, String message); | |
} | |
public class FileAppender extends Appender { | |
private OutputStream stream; | |
private Charset charset; | |
FileAppender(OutputStream os, Charset charset) throws IOException { | |
this.charset = charset; | |
this.stream = os; | |
} | |
FileAppender(String filename, Charset charset) throws IOException { | |
this(new FileOutputStream(filename), charset); | |
} | |
FileAppender(String filename) throws IOException { | |
this(new FileOutputStream(filename), Charset.forName("UTF-8")); | |
} | |
void setStream(OutputStream os) { | |
this.stream = os; | |
} | |
@Override | |
void append(Level level, String message) { | |
if(this.stream == null) { | |
return; | |
} | |
try { | |
this.stream.write(message.getBytes(charset)); | |
} catch(IOException e) { | |
System.err.println("Could not log message"); | |
} | |
} | |
} | |
public class ConsoleAppender extends FileAppender { | |
public ConsoleAppender(Charset charset) throws IOException { | |
super(System.out, charset); | |
} | |
public ConsoleAppender() throws IOException { | |
this(Charset.forName("UTF-8")); | |
} | |
} | |
private static final LinkedList<Appender> Appenders = new LinkedList<Appender>(); | |
private static Level level; | |
public static void addAppender(Appender appender) { | |
Appenders.add(appender); | |
} | |
public static boolean removeAppender(Appender appender) { | |
int i = Appenders.indexOf(appender); | |
if(i== -1) { | |
return false; | |
} | |
Appenders.remove(appender); | |
return true; | |
} | |
public static void setLevel(Level lvl) { | |
level = lvl; | |
} | |
public static Level getLevel() { | |
return level; | |
} | |
public static void Log(Level lvl, String message) { | |
if(level.getValue() >= lvl.getValue()) { | |
for(Appender a : Appenders) { | |
a.append(level, message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment