/*
 * Copyright 2017 Matt Sicker
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.musigma.logging;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;

/**
 * Simple appender based on {@link FileOutputStream} and {@link BufferedOutputStream}.
 */
public class FileOutputStreamAppender implements Appender {

    private final OutputStream out;
    private final Layout layout;

    public FileOutputStreamAppender(Path logFile, Layout layout) {
        try {
            this.out = new BufferedOutputStream(new FileOutputStream(logFile.toFile()));
            this.layout = layout;
        } catch (FileNotFoundException e) {
            throw new UncheckedIOException(e);
        }
    }

    @Override
    public synchronized void append(LogEvent event) {
        write(layout.encode(event));
    }

    private void write(ByteBuffer buf) {
        byte[] b = buf.array();
        try {
            out.write(b);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() throws Exception {
        out.flush();
        out.close();
    }
}

@@ -1100,16 +1100,139 @@
  layout;
+%0A    private final byte%5B%5D writeBuffer = new byte%5B8192%5D;%0A    private final ByteBuffer buf = ByteBuffer.allocateDirect(8192);
 %0A%0A    pu
@@ -1613,22 +1613,37 @@
         
-write(
+buf.clear();%0A        
 layout.e
@@ -1657,89 +1657,112 @@
 vent
-)
+, buf
 );%0A    
-%7D%0A%0A
     
-private void write(ByteBuffer buf) %7B%0A        byte%5B%5D b = buf.array(
+buf.flip();%0A        int length = buf.remaining();%0A        buf.get(writeBuffer, 0, length
 );%0A 
@@ -1796,17 +1796,38 @@
 t.write(
-b
+writeBuffer, 0, length
 );%0A     

Update FileOutputStreamAppender to use garbage-free encoding