gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:22:14 25 4
gpt4 key购买 nike

我在 tomcat 下运行一个网络应用程序,我已经像这样配置了日志记录(通过 contextInitialized Hook ):

    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 上设置任何内容来实现这一点。我是否遗漏了一些明显的东西,或者是否有办法实现它?

最佳答案

您可以使用 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");

}

}

关于java - 如何使用 java.util.logging.* 更改存储日志的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11937181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com