package logging;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This class allows us to log even uncatched exceptions.
* This is thought of like an AirBag. You dont want accidents (direct calls of
* printStackTrace(), or not catching possible Exceptions), but it's good to know that this must
* not end badly.
*/
public class SystemStreamLog extends PrintStream
{
private static final Log LOG = LogFactory.getLog(SystemStreamLog.class);
private PrintStream wrappedStream;
private SystemStreamLog(PrintStream wrap)
{
super(new NullOutputStream());
wrappedStream = wrap;
}
/**
* Overridden to find find and LOG Throwables.
*/
public void println(Object obj)
{
if(obj instanceof Throwable)
{
LOG.fatal("Uncaught Exception", (Throwable)obj);
}
wrappedStream.println(obj);
}
/**
* Replaces the System.err Stream with a special Version that will LOG Exceptions
* even if they have not been catched.
*/
public static void redirectSystemErr()
{
System.setErr(new SystemStreamLog(System.err));
}
/**
* Replaces the System.out Stream with a special Version that will LOG Exceptions
* even if they have not been catched.
* This will normally not be needed, because Exceptions will be output to the System.err, so this
* is just for paranoids who expect programmers to print their Exceptions to System.out.
*/
public static void redirectSystemOut()
{
System.setOut(new SystemStreamLog(System.out));
}
public static void main(String[] args)
{
SystemStreamLog.redirectSystemErr();
//just to create a OutOfMemoryError
List<String> list = new ArrayList<String>();
while(true)
{
list.add("HALLO");
}
}
}
class NullOutputStream extends OutputStream
{
public void write(int b) throws IOException
{}
public void write(byte[] b) throws IOException
{}
public void write(byte[] b, int off, int len) throws IOException
{}
}
|
News:
|
|
|
|
|
public aspect ExceptionLoggingAspect {
before (Exception e): handler(Exception+) && args(e) {
System.err.println("Caught by aspect: " + e.toString());
e.printStackTrace();
}
}|
|
|
|
|
|
|
|
[code]try
{
}
catch(OutOfMemoryError err)
{
LOG.fatal("Problem",err);
}
}