/**
 * Copyright (c) 2010-2012 EBM WebSourcing, 2012-2015 Linagora
 * 
 * This program/library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or (at your
 * option) any later version.
 * 
 * This program/library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program/library; If not, see <http://www.gnu.org/licenses/>
 * for the GNU Lesser General Public License version 2.1.
 */
package org.ow2.petals.log.handler;

import java.io.IOException;
import java.util.LinkedList;
import java.util.logging.FileHandler;
import java.util.logging.LogRecord;

/**
 * Stores logs in a list
 * 
 * @author Mathieu CARROLLE - EBM WebSourcing
 * 
 */
public class TestFileHandler extends FileHandler {

    private final LinkedList<String> logEntries;

    public TestFileHandler(String identifier) throws IOException {
        super("%t/" + identifier + "-%u", false);
        logEntries = new LinkedList<String>();
    }

    public TestFileHandler() throws IOException {
        this("log");
    }

    @Override
    public synchronized void publish(LogRecord record) {
        if (isLoggable(record)) {
            String entry = this.getFormatter().format(record);
            if (entry.endsWith("\n")) {
                entry = entry.substring(0, entry.length() - 1);
            }
            logEntries.add(entry);
        }
        super.publish(record);
    }

    @SuppressWarnings("unchecked")
    public LinkedList<String> getLogEntries() {
        return (LinkedList<String>) logEntries.clone();
    }

    @Override
    public void close() throws SecurityException {
        logEntries.clear();
        super.close();
    }
}
