Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logback and SLF4J programmatic configuration

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.

like image 949
Arsene Avatar asked Oct 01 '22 18:10

Arsene


1 Answers

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.

like image 56
jotomo Avatar answered Oct 05 '22 12:10

jotomo