使用 Logback 时出错

Error using Logback

我在 TCP 服务器上工作,我正在尝试添加日志记录。我决定使用 Logback。这是我的代码:

final static Logger logger = LoggerFactory.getLogger(Ecmg.class);

public static void main(String[] args)
{
    new Ecmg(args);
}

public Ecmg(String[] args) {

    logger.info("Hello world.");

    System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "/src/main/resources/logback.xml");
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    StatusPrinter.print(lc);

    waitForConnection();
}

不幸的是,我得到以下输出:

[main] INFO Ecmg - Hello world. 
Exception in thread "main" java.lang.ClassCastException: org.slf4j.simple.SimpleLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext at Ecmg.<init>(Ecmg.java:41) at Ecmg.main(Ecmg.java:29) 
Process finished with exit code 1

显然,下面一行是问题所在:LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();。我是按照教程写的,这应该可以工作。这是我的 pom.xml :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>Server</groupId>
<artifactId>Server</artifactId>
<version>1.0-SNAPSHOT</version>



<dependencies>
    <dependency>
        <groupId>io.vertx</groupId>
        <artifactId>vertx-core</artifactId>
        <version>3.5.1</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.8.0-beta2</version>
    </dependency>
</dependencies>

如果它很重要,我正在使用 java 8 和 Intellij 2018.1.

我的问题是:为什么会出现此错误,我该如何解决

注意: 除了这个 SO question,我在 Internet 上找不到任何可能与之相关的内容。但它还没有解决,none 提出的答案对我有用。

提前致谢!

SLF4J 是用于日志记录的标准化接口。您使用它的 API 进行日志记录,并在您的类路径上有一个 binding 用于您要使用的实际日志记录框架。

如果您的 LoggerFactory.getILoggerFactory()SimpleLoggerFactory,那么您使用的是 SimpleLogger 绑定。你说你决定使用 Logback,但实际上你使用的是 SLF4J SimpleLogger。

为了使用 Logback,您需要确保它在您的类路径中,并且您的类路径中没有其他 SLF4J 绑定。由于您正在使用 Maven 来管理依赖项,因此您可能希望 运行 "mvn dependency:tree" 查看所有依赖项的列表,以及您的依赖项带来的内容。这可能会帮助您找出其他绑定你正在使用。

旨在与 SLF4J 一起使用的行为良好的库将只包含 slf4j-api,因为绑定应该仅由主应用程序使用。如果你有一个行为不佳的库试图使用它自己的绑定,你可能需要使用 Maven 来 exclude 该绑定。

此外,使用 <dependencyManagement> sections in your POM to ensure that all your dependencies use the same version of slf4j-api and don't try to all include their own separate version, as well as using the maven-enforcer-plugin's bannedDependencies 规则通常有助于确保您在将来进行更改时不会搞砸,并且不小心将另一个日志记录框架包含到您的项目中。