1

我在 tomcat 下运行一个网络应用程序,并且我已经配置了这样的日志记录(通过 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/ 中创建的,例如 /var/lib/tomcat6/myapp_2012-08-13_0.log。我想将其更改为 /var/log/myapp/ ,例如: /var/log/myapp/myapp_2012-08-13_0.log 我没有看到任何我可以在 FileLogger 上设置来实现这一点。我错过了一些明显的东西,还是有办法实现它?

4

1 回答 1

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

    }

}
于 2012-08-13T15:32:41.777 回答