Java Logging With Abstract Classes

后端 未结 6 1235
闹比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条回答
  •  礼貌的吻别
    2021-01-30 16:23

    I wouldn't do either. Instead I would make it use the correct class in both cases.

    public abstract class AbstractFoo {
        protected final Log log = LogFactory.getLog(getClass());
    
        ...
    }
    
    public class Foo extends AbstractFoo {
        public void someMethod() {
            log.info("Using abstract log");
        }
    }
    

    If you are not doing lots of logging (which is a good idea anyway) you can use a method instead.

    public abstract class AbstractFoo {
        protected Log log() { return LogFactory.getLog(getClass()); }
    
        ...
    }
    

    If there is a class which calls this a lot you can override it to give you a cached instance.

提交回复
热议问题