如何使用java.util.logging更改存储日志的目录。*

时间:2012-08-13 15:11:25

标签: java tomcat logging

我正在tomcat下运行一个Web应用程序,我已经配置了这样的日志记录(通过contextInitialized钩子):

    Logger rootLogger = Logger.getLogger("");
    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    FileHandler logHandler = new FileHandler(
        "myapp_" + date + "_%u.log",
        524288000, // 500 MB max size
        1, // one log file at a time
        true // if it exists: append, don't overwrite
    );
    Level defaultLevel = Level.INFO;
    logHandler.setFormatter(new XMLFormatter());
    logHandler.setLevel(defaultLevel);
    for (Handler h : rootLogger.getHandlers()) {
        rootLogger.removeHandler(h);
    }
    rootLogger.setLevel(defaultLevel);
    rootLogger.addHandler(logHandler);

不幸的是,日志不会在/ var / log下创建。它们在/ var / lib / tomcat6 / like /var/lib/tomcat6/myapp_2012-08-13_0.log中创建。我想把它改成/ var / log / myapp / like:/var/log/myapp/myapp_2012-08-13_0.log我没有看到我可以在FileLogger上设置任何东西来实现这一点。我错过了一些明显的东西,还是有办法实现它?

1 个答案:

答案 0 :(得分:1)

您可以使用JVM属性前置到文件名。在下面的示例传递中,例如 -Dlog_directory = C:\ logs

package sample;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;

import org.apache.commons.lang.StringUtils;

public class stackoverflow11937181 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Logger rootLogger = Logger.getLogger("");
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String logDirectory = System.getProperty("log_directory");
        String logFile = (logDirectory == null ? StringUtils.EMPTY : logDirectory) + "/myapp_" + date + "_%u.log";
        try {
            FileHandler logHandler = new FileHandler(logFile, 524288000, // 500 MB max size
                    1, // one log file at a time
                    true // if it exists: append, don't overwrite
            );
            Level defaultLevel = Level.INFO;
            logHandler.setFormatter(new XMLFormatter());
            logHandler.setLevel(java.util.logging.Level.FINE);
            for (Handler h : rootLogger.getHandlers()) {
                rootLogger.removeHandler(h);
            }
            rootLogger.setLevel(defaultLevel);
            rootLogger.addHandler(logHandler);

        }
        catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        rootLogger.log(Level.FINE, "sample");

    }

}