View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.appender;
18  
19  import java.io.Serializable;
20  import java.util.concurrent.locks.Lock;
21  import java.util.concurrent.locks.ReadWriteLock;
22  import java.util.concurrent.locks.ReentrantReadWriteLock;
23  
24  import org.apache.logging.log4j.core.Filter;
25  import org.apache.logging.log4j.core.Layout;
26  import org.apache.logging.log4j.core.LogEvent;
27  
28  /**
29   * Appends log events as bytes to a byte output stream. The stream encoding is defined in the layout.
30   * 
31   * @param <M> The kind of {@link OutputStreamManager} under management
32   */
33  public abstract class AbstractOutputStreamAppender<M extends OutputStreamManager> extends AbstractAppender {
34  
35      private static final long serialVersionUID = 1L;
36  
37      /**
38       * Immediate flush means that the underlying writer or output stream will be flushed at the end of each append
39       * operation. Immediate flush is slower but ensures that each append request is actually written. If
40       * <code>immediateFlush</code> is set to {@code false}, then there is a good chance that the last few logs events
41       * are not actually written to persistent media if and when the application crashes.
42       */
43      private final boolean immediateFlush;
44  
45      private final M manager;
46  
47      private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
48      private final Lock readLock = rwLock.readLock();
49  
50      /**
51       * Instantiates a WriterAppender and set the output destination to a new {@link java.io.OutputStreamWriter}
52       * initialized with <code>os</code> as its {@link java.io.OutputStream}.
53       * 
54       * @param name The name of the Appender.
55       * @param layout The layout to format the message.
56       * @param manager The OutputStreamManager.
57       */
58      protected AbstractOutputStreamAppender(final String name, final Layout<? extends Serializable> layout,
59              final Filter filter, final boolean ignoreExceptions, final boolean immediateFlush, final M manager) {
60          super(name, filter, layout, ignoreExceptions);
61          this.manager = manager;
62          this.immediateFlush = immediateFlush;
63      }
64  
65      /**
66       * Gets the immediate flush setting.
67       * 
68       * @return immediate flush.
69       */
70      public boolean getImmediateFlush() {
71          return immediateFlush;
72      }
73  
74      /**
75       * Gets the manager.
76       * 
77       * @return the manager.
78       */
79      public M getManager() {
80          return manager;
81      }
82  
83      @Override
84      public void start() {
85          if (getLayout() == null) {
86              LOGGER.error("No layout set for the appender named [" + getName() + "].");
87          }
88          if (manager == null) {
89              LOGGER.error("No OutputStreamManager set for the appender named [" + getName() + "].");
90          }
91          super.start();
92      }
93  
94      @Override
95      public void stop() {
96          super.stop();
97          manager.release();
98      }
99  
100     /**
101      * Actual writing occurs here.
102      * <p>
103      * Most subclasses of <code>AbstractOutputStreamAppender</code> will need to override this method.
104      * </p>
105      * 
106      * @param event The LogEvent.
107      */
108     @Override
109     public void append(final LogEvent event) {
110         readLock.lock();
111         try {
112             final byte[] bytes = getLayout().toByteArray(event);
113             if (bytes.length > 0) {
114                 manager.write(bytes);
115                 if (this.immediateFlush || event.isEndOfBatch()) {
116                     manager.flush();
117                 }
118             }
119         } catch (final AppenderLoggingException ex) {
120             error("Unable to write to stream " + manager.getName() + " for appender " + getName());
121             throw ex;
122         } finally {
123             readLock.unlock();
124         }
125     }
126 
127 }