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.BufferedOutputStream;
20  import java.io.File;
21  import java.io.FileNotFoundException;
22  import java.io.FileOutputStream;
23  import java.io.IOException;
24  import java.io.OutputStream;
25  import java.nio.channels.FileChannel;
26  import java.nio.channels.FileLock;
27  
28  
29  /**
30   * Manages actual File I/O for File Appenders.
31   */
32  public class FileManager extends OutputStreamManager {
33  
34      private static final FileManagerFactory FACTORY = new FileManagerFactory();
35  
36      private final boolean isAppend;
37      private final boolean isLocking;
38  
39      protected FileManager(final String fileName, final OutputStream os, final boolean append, final boolean locking) {
40          super(os, fileName);
41          this.isAppend = append;
42          this.isLocking = locking;
43      }
44  
45      /**
46       * Returns the FileManager.
47       * @param fileName The name of the file to manage.
48       * @param append true if the file should be appended to, false if it should be overwritten.
49       * @param locking true if the file should be locked while writing, false otherwise.
50       * @param bufferedIO true if the contents should be buffered as they are written.
51       * @return A FileManager for the File.
52       */
53      public static FileManager getFileManager(final String fileName, final boolean append, boolean locking,
54                                               final boolean bufferedIO) {
55  
56          if (locking && bufferedIO) {
57              locking = false;
58          }
59          return (FileManager) getManager(fileName, new FactoryData(append, locking, bufferedIO), FACTORY);
60      }
61  
62      @Override
63      protected synchronized void write(final byte[] bytes, final int offset, final int length)  {
64  
65          if (isLocking) {
66              final FileChannel channel = ((FileOutputStream) getOutputStream()).getChannel();
67              try {
68                  /* Lock the whole file. This could be optimized to only lock from the current file
69                     position. Note that locking may be advisory on some systems and mandatory on others,
70                     so locking just from the current position would allow reading on systems where
71                     locking is mandatory.  Also, Java 6 will throw an exception if the region of the
72                     file is already locked by another FileChannel in the same JVM. Hopefully, that will
73                     be avoided since every file should have a single file manager - unless two different
74                     files strings are configured that somehow map to the same file.*/
75                  final FileLock lock = channel.lock(0, Long.MAX_VALUE, false);
76                  try {
77                      super.write(bytes, offset, length);
78                  } finally {
79                      lock.release();
80                  }
81              } catch (final IOException ex) {
82                  throw new AppenderRuntimeException("Unable to obtain lock on " + getName(), ex);
83              }
84  
85          } else {
86              super.write(bytes, offset, length);
87          }
88      }
89  
90      /**
91       * Returns the name of the File being managed.
92       * @return The name of the File being managed.
93       */
94      public String getFileName() {
95          return getName();
96      }
97  
98      /**
99       * Returns the append status.
100      * @return true if the file will be appended to, false if it is overwritten.
101      */
102     public boolean isAppend() {
103         return isAppend;
104     }
105 
106     /**
107      * Returns the lock status.
108      * @return true if the file will be locked when writing, false otherwise.
109      */
110     public boolean isLocking() {
111         return isLocking;
112     }
113 
114     /**
115      * Factory Data.
116      */
117     private static class FactoryData {
118         private final boolean append;
119         private final boolean locking;
120         private final boolean bufferedIO;
121 
122         /**
123          * Constructor.
124          * @param append Append status.
125          * @param locking Locking status.
126          * @param bufferedIO Buffering flag.
127          */
128         public FactoryData(final boolean append, final boolean locking, final boolean bufferedIO) {
129             this.append = append;
130             this.locking = locking;
131             this.bufferedIO = bufferedIO;
132         }
133     }
134 
135     /**
136      * Factory to create a FileManager.
137      */
138     private static class FileManagerFactory implements ManagerFactory<FileManager, FactoryData> {
139 
140         /**
141          * Create a FileManager.
142          * @param name The name of the File.
143          * @param data The FactoryData
144          * @return The FileManager for the File.
145          */
146         public FileManager createManager(final String name, final FactoryData data) {
147             final File file = new File(name);
148             final File parent = file.getParentFile();
149             if (null != parent && !parent.exists()) {
150                 parent.mkdirs();
151             }
152 
153             OutputStream os;
154             try {
155                 os = new FileOutputStream(name, data.append);
156                 if (data.bufferedIO) {
157                     os = new BufferedOutputStream(os);
158                 }
159                 return new FileManager(name, os, data.append, data.locking);
160             } catch (final FileNotFoundException ex) {
161                 LOGGER.error("FileManager (" + name + ") " + ex);
162             }
163             return null;
164         }
165     }
166 
167 }