I am using Logback and SLF4J in a tomcat based web application. I am not using any logback.xml file. Everything is done programmatically. However from time to time I got the following error message:
java.lang.ClassCastException: org.slf4j.helpers.SubstituteLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext.
and this the portion of code that throws that exception:
LoggerContext logCtx = (LoggerContext) LoggerFactory
.getILoggerFactory();
I would like to know whether I am doing something wrong or not. Please assist.
As far as I can tell this is caused by SLF4J using an intermediate factory when the backing logging implementation hasn't been initialized yet. If you ask the LoggerFactory for a logger first, e.g. the root logger, this will initalize Logback and after that your code should get a suitable LoggerContext. I encountered this due to my loggers being lazily created on first access and the first log statements came only after I tried to retrieve the LoggerContext. Having the usual private static final Logger = LoggerFactory.getLogger("...")
line in the class retrieving the LoggerContext will also have the same effect, though the connection is not obvious then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With