增加监控,针对堆栈包含 org.apache.logging.log4j.core.async.AsyncLoggerConfigDisruptor.enqueue 的 java monitor block 事件进行监控,如果发现时间过长或者数量很多的事件则报警或者重建进程
1. 配置 Appender 的 immediateFlush 为 false我们可以配置 Appender 的 immediateFlush 为 false,例如:
<RollingFile append="true" filePattern="./app.log-%d{yyyy.MM.dd.HH}" immediateFlush="false"> <PatternLayout pattern="${logFormat}"/> <Policies> <TimeBasedTriggeringPolicy interval="1" modulate="true"/> </Policies> <DirectWriteRolloverStrategy maxFiles="72"/> </RollingFile>这里的原理对应源码:
AbstractOutputStreamAppender.java
protected void directEncodeEvent(final LogEvent event) { getLayout().encode(event, manager); //如果配置了 immdiateFlush (默认为 true)或者当前事件是 EndOfBatch if (this.immediateFlush || event.isEndOfBatch()) { manager.flush(); } }那么对于 Log4j2 Disruptor 异步日志来说,什么时候 LogEvent 是 EndOfBatch 呢?是在消费到的 index 等于生产发布到的最大 index 的时候,这也是比较符合性能设计考虑,即在没有消费完的时候,尽可能地不 flush,消费完当前所有的时候再去 flush:
BatchEventProcessor.java
private void processEvents() { T event = null; long nextSequence = sequence.get() + 1L; while (true) { try { final long availableSequence = sequenceBarrier.waitFor(nextSequence); if (batchStartAware != null) { batchStartAware.onBatchStart(availableSequence - nextSequence + 1); } while (nextSequence <= availableSequence) { event = dataProvider.get(nextSequence); //这里 nextSequence == availableSequence 就是 EndOfBatch eventHandler.onEvent(event, nextSequence, nextSequence == availableSequence); nextSequence++; } sequence.set(availableSequence); } catch (final TimeoutException e) { notifyTimeout(sequence.get()); } catch (final AlertException ex) { if (running.get() != RUNNING) { break; } } catch (final Throwable ex) { exceptionHandler.handleEventException(ex, nextSequence, event); sequence.set(nextSequence); nextSequence++; } } } 2. 增加基于 JFR 事件监控这个需要 Java 14 以上的版本
Configuration config = Configuration.getConfiguration("default"); //设置监控的锁 block 时间超过多少就会采集 config.getSettings().put("jdk.JavaMonitorEnter#threshold", "1s"); try (var es = new RecordingStream(config)) { es.onEvent("jdk.JavaMonitorEnter", recordedEvent -> { //如果堆栈包含我们关注的,则报警 if (recordedEvent.getStackTrace().getFrames().stream().anyMatch(recordedFrame -> recordedFrame.toString().contains("org.apache.logging.log4j.core.async.AsyncLoggerConfigDisruptor.enqueue"))) { System.out.println("Alarm: " + recordedEvent); } }); es.start(); }微信搜索“我的编程喵”关注公众号,每日一刷,轻松提升技术,斩获各种offer: