log4j试图登录该文件

时间:2016-07-26 07:24:17

标签: java logging log4j

我正在尝试使用log4j将其记录在文件中 这是代码

    protected static Logger logger = Logger.getLogger(Application.class);
    private static final String DIRECTORY = "/Users/me/Desktop";
    private static final String EXTENSION = ".log";

    protected void setupLogger(String fileName) {
        SimpleLayout layout = new SimpleLayout();
        FileAppender appender = new FileAppender(layout, DIRECTORY + "/logs/" + fileName + EXTENSION, false);
        logger.addAppender(appender);
        logger.setLevel((Level) Level.DEBUG);
    }

这是我使用http://pastebin.com/vXdFtzSU

的pom

我得到的堆栈跟踪就在这里

Error:(40, 28) java: incompatible types: org.apache.log4j.FileAppender cannot be converted to org.apache.log4j.Appender

我正在尝试按照这个答案configure log4j to log to custom file at runtime

3 个答案:

答案 0 :(得分:2)

您好尝试改变您的maven依赖项添加此依赖项:

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

并更改spring boot依赖项以排除日志记录依赖项:

      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
          <exclusions>
            <exclusion>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
          </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
          <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

然后添加try / catch语句:

    protected void setupLogger(String fileName) {

        try {
            SimpleLayout layout = new SimpleLayout();
            FileAppender appender;
            appender = new FileAppender(layout, DIRECTORY + "/logs/" +        fileName + EXTENSION, false); 
            logger.addAppender(appender);
            logger.setLevel((Level) Level.DEBUG);
        } catch (IOException e) { 
            e.printStackTrace();
        }
    }

答案 1 :(得分:0)

看起来你在运行时使用的是不同版本的libraray,而不是在编译时。如果类型真的不兼容会产生编译器错误。如果您在Tomcat等特殊环境中运行程序,请检查是否安装了相同版本的log4j。

答案 2 :(得分:0)

为什么不使用log4j.properties这是一个非常简单的配置打印文件。

log4j.logger.register=INFO,R7
log4j.appender.R7=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R7.DatePattern='.'yyyyMMdd
log4j.appender.R7.File=/appLogs/address/logFile.log
log4j.appender.R7.layout=org.apache.log4j.PatternLayout
log4j.appender.R7.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss} | %m%n


private static final Logger logger = Logger.getLogger("register");

logger.info("print to file and console");