1 22 package org.jboss.logging.util; 23 24 import java.io.IOException ; 25 import java.io.PrintStream ; 26 27 import org.apache.log4j.Logger; 28 import org.apache.log4j.Level; 29 30 31 41 public class LoggerStream 42 extends PrintStream 43 { 44 49 public static final boolean TRACE = 50 getBoolean(LoggerStream.class.getName() + ".trace", false); 51 52 53 private static boolean getBoolean(String name, boolean defaultValue) 54 { 55 String value = System.getProperty(name, null); 56 if (value == null) 57 return defaultValue; 58 return new Boolean (value).booleanValue(); 59 } 60 61 private Logger logger; 62 private Level level; 63 private boolean inWrite; 64 private boolean issuedWarning; 65 66 69 public LoggerStream(final Logger logger) 70 { 71 this(logger, Level.INFO, System.out); 72 } 73 74 78 public LoggerStream(final Logger logger, 79 final Level level, 80 final PrintStream ps) 81 { 82 super(ps); 83 this.logger = logger; 84 this.level = level; 85 } 86 87 public void println(String msg) 88 { 89 if( msg == null ) 90 msg = "null"; 91 byte[] bytes = msg.getBytes(); 92 write(bytes, 0, bytes.length); 93 } 94 95 public void println(Object msg) 96 { 97 if( msg == null ) 98 msg = "null"; 99 byte[] bytes = msg.toString().getBytes(); 100 write(bytes, 0, bytes.length); 101 } 102 103 public void write(byte b) 104 { 105 byte[] bytes = {b}; 106 write(bytes, 0, 1); 107 } 108 109 private ThreadLocal recursiveCheck = new ThreadLocal (); 110 public void write(byte[] b, int off, int len) 111 { 112 Boolean recursed = (Boolean )recursiveCheck.get(); 113 if (recursed != null && recursed.equals(Boolean.TRUE)) 114 { 115 119 if( issuedWarning == false ) 120 { 121 String msg = "ERROR: invalid console appender config detected, console stream is looping"; 122 try 123 { 124 out.write(msg.getBytes()); 125 } 126 catch(IOException ignore) 127 { 128 } 129 issuedWarning = true; 130 } 131 return; 132 } 133 134 while( len > 0 && (b[len-1] == '\n' || b[len-1] == '\r') && len > off ) 136 len --; 137 138 if (len != 0) 142 { 143 String msg = new String (b, off, len); 144 recursiveCheck.set(Boolean.TRUE); 145 if (TRACE) 146 { 147 logger.log(level, msg, new Throwable ()); 148 } 149 else 150 { 151 logger.log(level, msg); 152 } 153 recursiveCheck.set(Boolean.FALSE); 154 } 155 } 156 } 157 | Popular Tags |