使用gradle构建框架使用log4j包构建app的错误

时间:2018-05-23 18:37:01

标签: java gradle log4j build.gradle log4j2

我使用gradle创建了一个简单的java项目,从“gradle init --type java-application”开始。

主java文件的内容 - “App.java”:

import org.apache.log4j.Logger;
import java.io.*;
import java.sql.SQLException;
import java.util.*;


public class App {

    public static void main(String[] args) {
        System.out.println("Howdy");
    }
}

文件内容“build.gradle”:

apply plugin: 'java'
apply plugin: 'application'

repositories {
    jcenter()
}

dependencies {
    compile 'com.google.guava:guava:21.0'
    testCompile 'junit:junit:4.12'

    // Following added by me for log4j
    compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.11.0'
    compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.11.0'

}

mainClassName = 'App'

log4j jar文件似乎已被gradle成功下载:

/home/ahmed/.gradle/caches/modules-2/files-2.1/org.apache.logging.log4j/log4j-api/2.11.0/bede79a3f150711634a3047985517431bf6499f2/log4j-api-2.11.0.jar
/home/ahmed/.gradle/caches/modules-2/files-2.1/org.apache.logging.log4j/log4j-core/2.11.0/e6b751e02120c08702d98750f6a80bc25343b7f5/log4j-core-2.11.0.jar

〜/ .gradle目录中有一堆log4j jar / pom文件。 当我尝试构建时,我收到以下构建错误:

$ gradle build
:compileJava
/home/ahmed/temp/javatut/gradle-demo/src/main/java/App.java:5: error: package org.apache.log4j does not exist
import org.apache.log4j.Logger;
                       ^
1 error
:compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 0.808 secs

我是gradle / java的新手。任何帮助将不胜感激。

谢谢你, 艾哈迈德。

1 个答案:

答案 0 :(得分:1)

build.gradle文件中,您指定了 log4j2 jars的依赖关系,但在代码中,您使用的是 log4j(版本1)类

import org.apache.log4j.Logger;

此语句指定Logger版本1中的log4j类。

log4j2中,它会更改为org.apache.logging.log4j.Logger -

import org.apache.logging.log4j.Logger;