1 17 package org.apache.log.output.io; 18 19 import java.io.IOException ; 20 import java.io.OutputStream ; 21 import org.apache.log.format.Formatter; 22 import org.apache.log.output.AbstractOutputTarget; 23 24 29 public class StreamTarget 30 extends AbstractOutputTarget 31 { 32 33 private OutputStream m_outputStream; 34 35 36 private String m_encoding; 37 38 46 public StreamTarget( final OutputStream outputStream, 47 final Formatter formatter, 48 final String encoding ) 49 { 50 super( formatter ); 51 m_encoding = encoding; 52 53 if( null != outputStream ) 54 { 55 setOutputStream( outputStream ); 56 open(); 57 } 58 } 59 60 66 public StreamTarget( final OutputStream outputStream, 67 final Formatter formatter ) 68 { 69 74 this( outputStream, formatter, null ); 75 } 76 77 83 protected synchronized void setOutputStream( final OutputStream outputStream ) 84 { 85 if( null == outputStream ) 86 { 87 throw new NullPointerException ( "outputStream property must not be null" ); 88 } 89 90 m_outputStream = outputStream; 91 } 92 93 98 protected synchronized void write( final String data ) 99 { 100 final OutputStream outputStream = m_outputStream; 103 104 if( null == outputStream ) 105 { 106 final String message = "Attempted to write data '" + data + "' to Null OutputStream"; 107 getErrorHandler().error( message, null, null ); 108 return; 109 } 110 111 try 112 { 113 byte[] bytes; 114 if( m_encoding == null ) 115 { 116 bytes = data.getBytes(); 117 } 118 else 119 { 120 bytes = data.getBytes( m_encoding ); 121 } 122 outputStream.write( bytes ); 123 outputStream.flush(); 124 } 125 catch( final IOException ioe ) 126 { 127 final String message = "Error writing data '" + data + "' to OutputStream"; 128 getErrorHandler().error( message, ioe, null ); 129 } 130 } 131 132 137 public synchronized void close() 138 { 139 super.close(); 140 shutdownStream(); 141 } 142 143 146 protected synchronized void shutdownStream() 147 { 148 final OutputStream outputStream = m_outputStream; 149 m_outputStream = null; 150 151 try 152 { 153 if( null != outputStream ) 154 { 155 if( ! ( System.out == outputStream && System.err == outputStream ) ) 157 { 158 outputStream.close(); 159 } 160 } 161 } 162 catch( final IOException ioe ) 163 { 164 getErrorHandler().error( "Error closing OutputStream", ioe, null ); 165 } 166 } 167 } 168 | Popular Tags |