Logback - Définir le nom du fichier journal par programme
DansLogback, il est facile de définir un nom de fichier journal par programmation:
-
En
logback.xml, déclare une variable comme${log.name} -
En Java, définissez la variable via
System.setProperty("log.name", "abc")
1. Exemple complet
1.1 A logback file, we will set the ${log.name} variable later.
src/main/resources/logback.xml
${USER_HOME}/${log.name}.error %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n ${USER_HOME}/${log.name}-${bySecond}.log %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{35} - %msg%n
1.2 In Java, just set the file name via System.setProperty
AntRunApp.java
package com.example.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AntRunApp {
private final Logger logger = LoggerFactory.getLogger(AntRunApp.class);
public static void main(String[] args) {
//Set this before the logger start.
System.setProperty("log.name", "example");
AntRunApp obj = new AntRunApp();
obj.start();
}
private void start() {
logger.debug("------ Starting Ant------");
//...
}
}
Sortie
Debug log file path /home/example/ant/logs/example-20150323.221959.log Error log file path /home/example/ant/logs/example.error
2. log.name.rir_IS_UNDEFINED.log
2.1 A common error, normally it is caused by the static logger. Par exemple.
AntRunApp.java
package com.example.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AntRunApp {
// static, this logger will be initialized before the program is run.
// All logs will be redirected to log.name.rir_IS_UNDEFINED.log
private static final Logger logger = LoggerFactory.getLogger(AntRunApp.class);
private void start() {
System.setProperty("log.name", "example");
logger.debug("------ Starting Ant------");
//...
}
}
To fix it, supprimez simplement le typestatic.
2.2 If you logs before the System.setProperty, this will also cause the common Logback variable UNDEFINED error.
AntRunApp.java
package com.example.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AntRunApp {
private final Logger logger = LoggerFactory.getLogger(AntRunApp.class);
private void start() {
//Please set the log name first!
logger.debug("------ Starting Ant------");
System.setProperty("log.name", "example");
}
}