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.util.concurrent.TimeUnit;
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.LogEvent;
26  import org.apache.logging.log4j.core.StringLayout;
27  
28  /**
29   * Appends log events as strings to a writer.
30   * 
31   * @param <M>
32   *            The kind of {@link WriterManager} under management
33   */
34  public abstract class AbstractWriterAppender<M extends WriterManager> extends AbstractAppender {
35  
36      /**
37       * Immediate flush means that the underlying writer will be flushed at the
38       * end of each append operation. Immediate flush is slower but ensures that
39       * each append request is actually written. If <code>immediateFlush</code>
40       * is set to {@code false}, then there is a good chance that the last few
41       * logs events are not actually written to persistent media if and when the
42       * application crashes.
43       */
44      protected final boolean immediateFlush;
45      private final M manager;
46      private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
47      private final Lock readLock = readWriteLock.readLock();
48  
49      /**
50       * Instantiates.
51       * 
52       * @param name
53       *            The name of the Appender.
54       * @param layout
55       *            The layout to format the message.
56       * @param manager
57       *            The OutputStreamManager.
58       */
59      protected AbstractWriterAppender(final String name, final StringLayout layout, final Filter filter,
60              final boolean ignoreExceptions, final boolean immediateFlush, final M manager) {
61          super(name, filter, layout, ignoreExceptions);
62          this.manager = manager;
63          this.immediateFlush = immediateFlush;
64      }
65  
66      /**
67       * Actual writing occurs here.
68       * <p>
69       * Most subclasses will need to override this method.
70       * </p>
71       * 
72       * @param event
73       *            The LogEvent.
74       */
75      @Override
76      public void append(final LogEvent event) {
77          readLock.lock();
78          try {
79              final String str = getStringLayout().toSerializable(event);
80              if (str.length() > 0) {
81                  manager.write(str);
82                  if (this.immediateFlush || event.isEndOfBatch()) {
83                      manager.flush();
84                  }
85              }
86          } catch (final AppenderLoggingException ex) {
87              error("Unable to write " + manager.getName() + " for appender " + getName() + ": " + ex);
88              throw ex;
89          } finally {
90              readLock.unlock();
91          }
92      }
93  
94      /**
95       * Gets the manager.
96       * 
97       * @return the manager.
98       */
99      public M getManager() {
100         return manager;
101     }
102 
103     public StringLayout getStringLayout() {
104         return (StringLayout) getLayout();
105     }
106 
107     @Override
108     public void start() {
109         if (getLayout() == null) {
110             LOGGER.error("No layout set for the appender named [{}].", getName());
111         }
112         if (manager == null) {
113             LOGGER.error("No OutputStreamManager set for the appender named [{}].", getName());
114         }
115         super.start();
116     }
117 
118     @Override
119     public boolean stop(final long timeout, final TimeUnit timeUnit) {
120         setStopping();
121         boolean stopped = super.stop(timeout, timeUnit, false);
122         stopped &= manager.stop(timeout, timeUnit);
123         setStopped();
124         return stopped;
125     }
126 }