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      /**
36       * Immediate flush means that the underlying writer or output stream
37       * will be flushed at the end of each append operation. Immediate
38       * flush is slower but ensures that each append request is actually
39       * written. If <code>immediateFlush</code> is set to
40       * {@code false}, then there is a good chance that the last few
41       * logs events are not actually written to persistent media if and
42       * when the application crashes.
43       */
44      protected final boolean immediateFlush;
45  
46      private volatile M manager;
47  
48      private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
49      private final Lock readLock = rwLock.readLock();
50      private final Lock writeLock = rwLock.writeLock();
51  
52      /**
53       * Instantiate a WriterAppender and set the output destination to a
54       * new {@link java.io.OutputStreamWriter} initialized with <code>os</code>
55       * as its {@link java.io.OutputStream}.
56       * @param name The name of the Appender.
57       * @param layout The layout to format the message.
58       * @param manager The OutputStreamManager.
59       */
60      protected AbstractOutputStreamAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
61                                             final boolean ignoreExceptions, final boolean immediateFlush,
62                                             final M manager) {
63          super(name, filter, layout, ignoreExceptions);
64          this.manager = manager;
65          this.immediateFlush = immediateFlush;
66      }
67  
68      /**
69       * Gets the manager.
70       * 
71       * @return the manager.
72       */
73      public M getManager() {
74          return manager;
75      }
76  
77      protected void replaceManager(final M newManager) {
78  
79          writeLock.lock();
80          try {
81              final M old = manager;
82              manager = newManager;
83              old.release();
84          } finally {
85              writeLock.unlock();
86          }
87  
88      }
89  
90      @Override
91      public void start() {
92          if (getLayout() == null) {
93              LOGGER.error("No layout set for the appender named [" + getName() + "].");
94          }
95          if (manager == null) {
96              LOGGER.error("No OutputStreamManager set for the appender named [" + getName() + "].");
97          }
98          super.start();
99      }
100 
101     @Override
102     public void stop() {
103         super.stop();
104         manager.release();
105     }
106 
107     /**
108      * Actual writing occurs here.
109      * <p/>
110      * <p>Most subclasses of <code>AbstractOutputStreamAppender</code> will need to
111      * override this method.
112      * @param event The LogEvent.
113      */
114     @Override
115     public void append(final LogEvent event) {
116         readLock.lock();
117         try {
118             final byte[] bytes = getLayout().toByteArray(event);
119             if (bytes.length > 0) {
120                 manager.write(bytes);
121                 if (this.immediateFlush || event.isEndOfBatch()) {
122                     manager.flush();
123                 }
124             }
125         } catch (final AppenderLoggingException ex) {
126             error("Unable to write to stream " + manager.getName() + " for appender " + getName());
127             throw ex;
128         } finally {
129             readLock.unlock();
130         }
131     }
132 }