Logback - ログファイル名をプログラムで設定する

Logback –プログラムでログファイル名を設定する

Logbackでは、プログラムでログファイル名を設定するのは簡単です。

  1. logback.xmlで、${log.name}のような変数を宣言します

  2. Javaでは、System.setProperty("log.name", "abc")を介して変数を設定します

1. 完全な例

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

        //...
    }

}

出力

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. 例えば。

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 itstaticタイプを削除するだけです。

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

    }

}