我有一个问题,因为我要开发一个简单但非常专业的日志系统,其他日志系统目前不适合我的需求。
编码:
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)
记录器是否也是这种情况?