Get live Log4J messages

前端 未结 3 476
南笙
南笙 2021-01-23 05:15

How do I get what is being written by log4j in central class which monitors all log4j logs in the application?

Thanks

Edit: I wish I would not have to read it fr

3条回答
  •  无人及你
    2021-01-23 05:53

    maybe your requirement is same with me. I just write a relevant class to realize it.

    public class FixedBufferAppender extends AppenderSkeleton {
        private LimitTailSizeList ll;
    
        public FixedBufferAppender(PatternLayout layOut, int size) {
            this.layout = layOut;
            ll = new LimitTailSizeList(size);
        }
    
        protected void append(LoggingEvent event) {
            String log = this.layout.format(event);
            ll.add(log);
        }
    
        public String getLatentLog() {
            StringBuffer sb = new StringBuffer(100000);
            for (Iterator iterator = ll.iterator(); iterator.hasNext();) {
                String log = (String) iterator.next();
                sb.append(log);
            }
            return sb.toString();
        }
    
        public void close() {
            ll.clear();
            ll = null;
            this.closed = true;
        }
    
        public boolean requiresLayout() {
            return true;
        }
    }
    
    public class LimitTailSizeList extends ArrayList {
        private int limitSize;
    
        public LimitTailSizeList(int limitSize){
            this.limitSize= limitSize;
        }
    
        public boolean add(Object o) {
            boolean add = super.add(o);
            if (size() > limitSize) {
                removeRange(0, size() - limitSize);
            }
            return add;
        }
    
        private void initAppender(int maxTailLine) {
            fba = new FixedBufferAppender(
                new PatternLayout("%d [%X{requestURIWithQueryString}] %-5p -[%t] %m  [%c{1}:%M %L] %n"),
                maxTailLine);
            Logger.getRootLogger().removeAppender("UI_APPENDER");
            fba.setName("UI_APPENDER");
            fba.setThreshold(org.apache.log4j.Level.DEBUG);
            Logger.getRootLogger().addAppender(fba);
        }
    }
    

提交回复
热议问题