1 17 package org.apache.log.output; 18 19 import org.apache.log.LogEvent; 20 import org.apache.log.LogTarget; 21 import org.apache.log.Priority; 22 23 35 public class MemoryTarget 36 extends AbstractTarget 37 { 38 private final LogEvent[] m_buffer; 40 41 private Priority m_threshold; 43 44 private LogTarget m_target; 46 47 private int m_used; 49 50 private int m_index; 52 53 private boolean m_overwrite; 55 56 62 public MemoryTarget( final LogTarget target, 63 final int size, 64 final Priority threshold ) 65 { 66 m_target = target; 67 m_buffer = new LogEvent[ size ]; 68 m_threshold = threshold; 69 open(); 70 } 71 72 77 protected synchronized void setOverwrite( final boolean overwrite ) 78 { 79 m_overwrite = overwrite; 80 } 81 82 87 protected synchronized void doProcessEvent( final LogEvent event ) 88 { 89 if( isFull() ) 91 { 92 if( m_overwrite ) 93 { 94 m_used--; 95 } 96 else 97 { 98 getErrorHandler().error( "Memory buffer is full", null, event ); 99 return; 100 } 101 } 102 103 if( 0 == m_used ) 104 { 105 m_index = 0; 106 } 107 else 108 { 109 m_index = ( m_index + 1 ) % m_buffer.length; 110 } 111 m_buffer[ m_index ] = event; 112 m_used++; 113 114 if( shouldPush( event ) ) 115 { 116 push(); 117 } 118 } 119 120 125 public final synchronized boolean isFull() 126 { 127 return m_buffer.length == m_used; 128 } 129 130 138 protected synchronized boolean shouldPush( final LogEvent event ) 139 { 140 return ( m_threshold.isLowerOrEqual( event.getPriority() ) || isFull() ); 141 } 142 143 146 public synchronized void push() 147 { 148 if( null == m_target ) 149 { 150 getErrorHandler().error( "Can not push events to a null target", null, null ); 151 return; 152 } 153 154 try 155 { 156 final int size = m_used; 157 int base = m_index - m_used + 1; 158 if( base < 0 ) 159 { 160 base += m_buffer.length; 161 } 162 163 for( int i = 0; i < size; i++ ) 164 { 165 final int index = ( base + i ) % m_buffer.length; 166 167 m_target.processEvent( m_buffer[ index ] ); 169 170 m_buffer[ index ] = null; 172 m_used--; 173 } 174 } 175 catch( final Throwable throwable ) 176 { 177 getErrorHandler().error( "Unknown error pushing events.", throwable, null ); 178 } 179 } 180 } 181 | Popular Tags |