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  public abstract class AbstractOutputStreamAppender extends AbstractAppender {
32  
33      /**
34       * Immediate flush means that the underlying writer or output stream
35       * will be flushed at the end of each append operation. Immediate
36       * flush is slower but ensures that each append request is actually
37       * written. If <code>immediateFlush</code> is set to
38       * {@code false}, then there is a good chance that the last few
39       * logs events are not actually written to persistent media if and
40       * when the application crashes.
41       */
42      protected final boolean immediateFlush;
43  
44      private volatile OutputStreamManager manager;
45  
46      private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
47      private final Lock readLock = rwLock.readLock();
48      private final Lock writeLock = rwLock.writeLock();
49  
50      /**
51       * Instantiate a WriterAppender and set the output destination to a
52       * new {@link java.io.OutputStreamWriter} initialized with <code>os</code>
53       * as its {@link java.io.OutputStream}.
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, final Filter filter,
59                                             final boolean ignoreExceptions, final boolean immediateFlush,
60                                             final OutputStreamManager manager) {
61          super(name, filter, layout, ignoreExceptions);
62          this.manager = manager;
63          this.immediateFlush = immediateFlush;
64      }
65  
66      protected OutputStreamManager getManager() {
67          return manager;
68      }
69  
70      protected void replaceManager(final OutputStreamManager newManager) {
71  
72          writeLock.lock();
73          try {
74              final OutputStreamManager old = manager;
75              manager = newManager;
76              old.release();
77          } finally {
78              writeLock.unlock();
79          }
80  
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      * <p>Most subclasses of <code>AbstractOutputStreamAppender</code> will need to
104      * override this method.
105      * @param event The LogEvent.
106      */
107     @Override
108     public void append(final LogEvent event) {
109         readLock.lock();
110         try {
111             final byte[] bytes = getLayout().toByteArray(event);
112             if (bytes.length > 0) {
113                 manager.write(bytes);
114                 if (this.immediateFlush || event.isEndOfBatch()) {
115                     manager.flush();
116                 }
117             }
118         } catch (final AppenderLoggingException ex) {
119             error("Unable to write to stream " + manager.getName() + " for appender " + getName());
120             throw ex;
121         } finally {
122             readLock.unlock();
123         }
124     }
125 }