package org.xbib.logging.test;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.logging.Formatter;

import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level;
import org.xbib.logging.formatters.SimpleFormatter;
import org.xbib.logging.handlers.FileHandler;
import org.junit.jupiter.api.Test;

public class FileHandlerPerformanceTests {

    private static final Formatter testFormatter = new SimpleFormatter();

    public FileHandlerPerformanceTests() {
    }

    private static void initHandler(ExtHandler handler) throws UnsupportedEncodingException {
        handler.setFormatter(testFormatter);
        handler.setLevel(Level.ALL);
        handler.setAutoFlush(true);
        handler.setEncoding("utf-8");
        handler.setErrorManager(AssertingErrorManager.of());
    }

    private static void publish(final ExtHandler handler, final String msg) {
        handler.publish(new ExtLogRecord(Level.INFO, msg, null));
    }

    @Test
    public void testPerformance() throws Exception {
        final FileHandler handler = new FileHandler();
        initHandler(handler);
        final File tempFile = File.createTempFile("jblm-", ".log");
        tempFile.deleteOnExit();
        handler.setFile(tempFile);
        final long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            publish(handler, "Test message " + i);
        }
        // the result is system dependant and can therefore only be checked manually
        // a 'sluggish' build indicates a problem
        System.out.println((System.currentTimeMillis() - start));
    }
}
