Java Logging With Abstract Classes

后端 未结 6 1247
闹比i
闹比i 2021-01-30 16:13

I am working on a project, and am currently working on implementing some logging with log4j and I was curious about how I should go about implementing the logs. The two implemen

6条回答
  •  旧时难觅i
    2021-01-30 16:18

    The same can be achieved by playing with constructors. Add logger at the Base class level and set it from every Derived class using super(). There is the code :

    public abstract class AbstractFoo {
    
        protected Log log;  // base abstract class has a Log object.
    
        public AbstractFoo(Log logger) {   // parameterized constructor for logger, to be used by the derived class.
            this.log = logger;
        }
    
        public doSomething() {        // common method for all the derived classes.
          log.info("log something");
        }
        // rest of business logic.
    }
    
    public class Foo extends AbstractFoo {
    
        public Foo(){
            super(LogFactory.getLog(AbstractFoo.class));
        }
    
        public void someMethod() {
            log.info("Using own log");     // this uses its own logger.
        }
    }
    

提交回复
热议问题