0

我有一个问题,因为我要开发一个简单但非常专业的日志系统,其他日志系统目前不适合我的需求。

编码:

package customlogger;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author student
 */
public class CustomLogger implements Runnable {
    private BlockingQueue<String> queue;
    private List<LogConsumer> consumers;

    public CustomLogger() {
        this.queue = new LinkedBlockingQueue<>();
        this.consumers = new ArrayList<>();
    }

    @Override
    public void run() {
        while (true) {
            try {
                String message = queue.take();
                for (LogConsumer consumer : consumers) {
                    consumer.consume(message);
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(CustomLogger.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void log(String message) {
        queue.offer(message);
    }

    public void addConsumer(LogConsumer consumer) {
        if (consumers.contains(consumer)) {
            return;
        }
        consumers.add(consumer);
    }

    public void removeConsumer(LogConsumer consumer) {
        if (!consumers.contains(consumer)) {
            return;
        }
        consumers.remove(consumer);
    }
}

package customlogger;

/**
 *
 * @author student
 */
public interface LogConsumer {
    public void consume(String message);
}

package customlogger;

/**
 *
 * @author student
 */
public class SystemOutConsumer implements LogConsumer {
    @Override
    public void consume(String message) {
        System.out.println(message);
    }
}

创建代码:

LogConsumer systemOutConsumer = new SystemOutConsumer();

CustomLogger simpleLogger = new CustomLogger();
simpleLogger.addConsumer(systemOutConsumer);
Thread simpleLoggerThread = new Thread(simpleLogger);
simpleLoggerThread.start();

现在假设我想用 记录很多消息simpleLogger.log(message);,这会损害我的程序本身的性能吗?

CustomLogger在自己的线程中运行,因此不应该(直接)影响我的程序的性能,但是System.out.println(message)记录器是否也是这种情况?

4

1 回答 1

1

It will not affect performance of your main thread if you do it like this. But I would reconsider using existing logging framework since I don't see that you created anything that's not possible to do with log4j for example ... ...

于 2013-10-28T14:21:46.637 回答