Get live Log4J messages

前端 未结 3 470
南笙
南笙 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:40

    You can implement your own Appender and copy all logs on it using the normal config:

    log4j.rootLogger=WARN, file, other
    
    log4j.appender.file=org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=${catalina.home}/logs/log.log
    log4j.appender.file.MaxFileSize=10MB
    log4j.appender.file.MaxBackupIndex=10
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=%d{ISO8601} %p %t %c - %m%n
    
    log4j.appender.other=class.path.of.your.Appender
    
    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
  • 2021-01-23 05:53

    By providing log4j configuration that outputs log messages into a file or any other location.

    0 讨论(0)
提交回复
热议问题