How do I avoid “LoggerContext” Class cast exception when upgrading from SLF4J v1.x to 2.x and using logback?

  Kiến thức lập trình

I have the following code…

LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

When I upgrade from 1.x to 2.x of SLF4J along with ch.qos.logback:logback-classic:jar:1.2.13:compile this line starts failing with…

java.lang.ClassCastException: class org.slf4j.helpers.NOPLoggerFactory cannot be cast to class ch.qos.logback.classic.LoggerContext (org.slf4j.helpers.NOPLoggerFactory and ch.qos.logback.classic.LoggerContext are in unnamed module of loader 'app')

What should I do to avoid this? I tried…

import org.slf4j.LoggerFactory;

public class SLF4JInitializer {
    static {
        // Trigger SLF4J initialization
  public static void setup() throws ClassNotFoundException {
    // This will trigger the static initializer block in SLF4JInitializer

But I still get the same error.