普通はJakarta Commons Logging を使うのですが、ちょっとだけ java.util.logging.Logger について調べてみたのでサンプルプログラムを置いておきます。実行ディレクトリへtest.logというファイルでログを出力します。コンソール画面への出力はしないようにしています。
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class LoggingTest {
private static Logger logger = Logger.getLogger(“LoggingTest”);
static {
try {
FileHandler handler = new FileHandler(“./test.log”);
handler.setFormatter(new SimpleFormatter());
logger.setUseParentHandlers(false);
logger.addHandler(handler);
} catch(java.io.IOException e){
e.printStackTrace();
}
logger.info(“Logger start.”);
}
public void execute() {
logger.info(“This is a test.”);
}
public static void main(String[] args) {
LoggingTest test = new LoggingTest();
test.execute();
}
}
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class LoggingTest {
private static Logger logger = Logger.getLogger(“LoggingTest”);
static {
try {
FileHandler handler = new FileHandler(“./test.log”);
handler.setFormatter(new SimpleFormatter());
logger.setUseParentHandlers(false);
logger.addHandler(handler);
} catch(java.io.IOException e){
e.printStackTrace();
}
logger.info(“Logger start.”);
}
public void execute() {
logger.info(“This is a test.”);
}
public static void main(String[] args) {
LoggingTest test = new LoggingTest();
test.execute();
}
}
実行するには次の通り。
> javac LoggingTest.java
> java LoggingTest
>
> java LoggingTest
>
こんなtest.logファイルが実行ディレクトリに作成される。
2005/05/19 12:38:45 LoggingTest
情報: Logger start.
2005/05/19 12:38:46 LoggingTest execute
情報: This is a test.
情報: Logger start.
2005/05/19 12:38:46 LoggingTest execute
情報: This is a test.