使用SLF4J和Logback发出为日志创建文件的问题

时间:2020-09-17 10:09:07

标签: java logback slf4j

我想在特定文件夹中创建错误日志文件。该文件夹具有以下结构:

app 
  |_ application.jar
  |_ configuration.json
  |_ logs
      |_ log-error.log

我构建了程序包,并在使用命令行运行应用程序时: java -jar readExternalFilesFromJar-jar-with-dependencies.jar

我确实获得了以下结果:

[main] INFO fr.mydomain.app.ReadJson - Main Application called
[main] INFO fr.mydomain.app.JsonReader - getJson() method called
[main] ERROR fr.mydomain.app.ReadJson - Error message

在控制台上进行登录没有问题。我的问题是未创建日志文件。

我在pom.xml中添加了SLF4J和Logback依赖项:

<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.7.30</version>
</dependency>

<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>1.7.30</version>
</dependency>

<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-core</artifactId>
  <version>1.2.3</version>
</dependency>

<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.2.3</version>
</dependency>

我还尝试使用资源文件夹中的logback.xml文件配置Logback:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <timestamp key="times" datePattern="yyyyMMdd.HHmmss" />

    <appender name="STDOUT" class="ch.qos.logback.core.FileAppender">
        <file>${path}/${log.name}-${times}.log</file>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>${path}/${log.name}-${times}.log</file>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <logger name="fr.mydomain.app" level="debug" additivity="false">
        <appender-ref ref="FILE" />
    </logger>

    <logger name="fr.mydomain.app" level="error" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>

    <root level="error">
        <appender-ref ref="FILE" />
    </root>

</configuration>

在我的主类中,我希望能够配置日志文件的路径和名称。为什么要在java方法中配置这些值?原因很简单。我希望能够从配置文件中读取这些值。

我阅读了一些有关如何设置文件名和路径的文档: https://mkyong.com/logging/logback-set-log-file-name-programmatically/

为此,我添加了以下代码:

public class ReadJson {
    private static Logger logger = LoggerFactory.getLogger(ReadJson.class);

    public static void main( String[] args ) throws Exception {
        System.setProperty("path", "./logs");
        System.setProperty("log.name", "error");
        logger.info("Main Application called");
        // déclaration de variables

        System.setProperty("path", ".");
        System.setProperty("log.name", "error");
        ...
    }
}

1 个答案:

答案 0 :(得分:0)

我使用getLogger方法创建了LogConfigurer类:

public Logger getLogger(Configuration configuration, String docType) {
    ...
    String logFileName = "whateverILog";
    fileAppender = new FileAppender();
    fileAppender.setContext(loggerContext);
    fileAppender.setName("timestamp");
    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(Level.ERROR);
    fileAppender.setFile(logFolder + "\\"+ logFilename +".log");
    encoder.setContext(loggerContext);
    encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n");
    encoder.start();
    fileAppender.setEncoder(encoder);
    fileAppender.start();
    logger = loggerContext.getLogger(getClass().getSimpleName());
    logger.addAppender(fileAppender);

    // OPTIONAL: print logback internal status messages
    StatusPrinter.print(loggerContext);
    // log something
    logger.debug("Logger Implemented");
    return logger;
}

在主方法中,我调用:

LogConfigurer logConfigurer = new LogConfigurer();
Logger logger = logConfigurer.getLogger(configuration, docType);