0

I'm using Spring, log4j and slf4j. While trying to log some info from a @PostConstruct -annotated method log4j complains about not been yet initialized. When I later on log from this class log4j works OK.

private final static Logger log = LoggerFactory.getLogger(MyClass.class);

@PostConstruct
public void init() {
    log.info("initializing service");
}

Output:
log4j:WARN No appenders could be found for logger (mypackage.MyClass)

Log4j configuration is a a file-based one:

log4j.rootLogger=INFO, console   
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %-5p %c %x - %m%n
S. Pauk
  • 5,208
  • 4
  • 31
  • 41

1 Answers1

1

the PostConstruct methods are called by Spring container right after dependency injection is done, but before init-methods. So in post-construct class instance isn't fully initialised. I would suggest using InitializingBean or init-method for that purpose.

androberz
  • 744
  • 10
  • 25
  • I wouldn't like to switch a standard Java annotation for a spring-specific `init-method` so the question could be rephrased as 'how to make Spring to load log4j.properties resource earlier ?'. – S. Pauk Apr 23 '15 at 09:23
  • As you have to pass class to the LoggerFactory method, you need to have this class to be initialised before. So I dont think that you can do it earlier, you just can try doing the `log` variable non static. – androberz Apr 23 '15 at 09:51
  • @SergeyPauk do you find the solution ? – Jesus Zavarce Dec 05 '18 at 20:22