package org.jboss.logging.util;
import java.io.IOException;
import java.io.PrintStream;
import org.apache.log4j.Category;
import org.apache.log4j.Priority;
public class CategoryStream
extends PrintStream
{
public static final boolean TRACE =
getBoolean(CategoryStream.class.getName() + ".trace", false);
private static boolean getBoolean(String name, boolean defaultValue)
{
String value = System.getProperty(name, null);
if (value == null)
return defaultValue;
return new Boolean(value).booleanValue();
}
private Category category;
private Priority priority;
private boolean issuedWarning;
public CategoryStream(final Category category)
{
this(category, Priority.INFO, System.out);
}
public CategoryStream(final Category category,
final Priority priority,
final PrintStream ps)
{
super(ps);
this.category = category;
this.priority = priority;
}
public void println(String msg)
{
if( msg == null )
msg = "null";
byte[] bytes = msg.getBytes();
write(bytes, 0, bytes.length);
}
public void println(Object msg)
{
if( msg == null )
msg = "null";
byte[] bytes = msg.toString().getBytes();
write(bytes, 0, bytes.length);
}
public void write(byte b)
{
byte[] bytes = {b};
write(bytes, 0, 1);
}
private ThreadLocal recursiveCheck = new ThreadLocal();
public void write(byte[] b, int off, int len)
{
Boolean recursed = (Boolean)recursiveCheck.get();
if (recursed != null && recursed.equals(Boolean.TRUE))
{
if( issuedWarning == false )
{
String msg = "ERROR: invalid console appender config detected, console stream is looping";
try
{
out.write(msg.getBytes());
}
catch(IOException ignore)
{
}
issuedWarning = true;
}
return;
}
while( len > 0 && (b[len-1] == '\n' || b[len-1] == '\r') && len > off )
len --;
if (len != 0)
{
String msg = new String(b, off, len);
recursiveCheck.set(Boolean.TRUE);
if (TRACE)
{
category.log(priority, msg, new Throwable());
}
else
{
category.log(priority, msg);
}
recursiveCheck.set(Boolean.FALSE);
}
}
}