log4j注意事项

   1.不应该大范围,跨多线程共用loger对象。

代码1-1
public
void callAppenders(LoggingEvent event) { int writes = 0; for (Category c = this; c != null; c = parent) { synchronized (c) { if (aai != null) { writes += aai.appendLoopOnAppenders(event); } if (!additive) { break; } } } if (writes == 0) { repository.emitNoAppenderWarning(this); } }
代码1-1截取自Logger对象的父类Category类。可以看到其使用logger对象作为锁,如果大范围跨线程使用相同logger对象会造成大范围阻塞。

2.如果使用同步日志也不应该大范围跨线程使用相同appender对象。

出于outputstream的write方法的锁的使用。

3.如果使用异步日志也不应该大范围跨线程使用相同的AsyncAppender对象。

代码1-2
public
void append(final LoggingEvent event) { // // if dispatcher thread has died then // append subsequent events synchronously // See bug 23021 if ((dispatcher == null) || !dispatcher.isAlive() || (bufferSize <= 0)) { synchronized (appenders) { appenders.appendLoopOnAppenders(event); } return; } // Set the NDC and thread name for the calling thread as these // LoggingEvent fields were not set at event creation time. event.getNDC(); event.getThreadName(); // Get a copy of this thread's MDC. event.getMDCCopy(); if (locationInfo) { event.getLocationInformation(); } synchronized (buffer) { while (true) { int previousSize = buffer.size(); if (previousSize < bufferSize) { buffer.add(event); // // if buffer had been empty // signal all threads waiting on buffer // to check their conditions. // if (previousSize == 0) { buffer.notifyAll(); } break; } // // Following code is only reachable if buffer is full // // // if blocking and thread is not already interrupted // and not the dispatcher then // wait for a buffer notification boolean discard = true; if (blocking && !Thread.interrupted() && Thread.currentThread() != dispatcher) { try { buffer.wait(); discard = false; } catch (InterruptedException e) { // // reset interrupt status so // calling code can see interrupt on // their next wait or sleep. Thread.currentThread().interrupt(); } } // // if blocking is false or thread has been interrupted // add event to discard map. // if (discard) { String loggerName = event.getLoggerName(); DiscardSummary summary = (DiscardSummary) discardMap.get(loggerName); if (summary == null) { summary = new DiscardSummary(event); discardMap.put(loggerName, summary); } else { summary.add(event); } break; } } } }
 
 

代码1-2取自AsyncAppender,可以看到使用AsyncAppender对象的buffer作为锁。

 
 

转载于:https://www.cnblogs.com/barker/p/4866066.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值