Search code examples
javalogbackslf4j

Issue creating file for logs with SLF4J and Logback


I want to create an error log file in a specific folder. The folder has the following structure:

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

I build the package and when I run the application with command line : java -jar readExternalFilesFromJar-jar-with-dependencies.jar

I do obtain the following result:

[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

I do not have issue making a log on console. My issue is that the log file is not created.

I added SLF4J and Logback dependencies in my pom.xml:

<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>

I also tried to configure Logback with a logback.xml file in my resource folder:

<?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>

In my main class I want to be able to configure the log file path and name. Why configuring those values in a java method ? the reason is rather simple. I want to be able to read those values from a configuration file.

I read some documentation on how to set file name and path : https://mkyong.com/logging/logback-set-log-file-name-programmatically/

For this I added the following code :

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");
        ...
    }
}

Solution

  • I created a LogConfigurer class with a getLogger method:

    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;
    }
    

    In the main method I call :

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