コードからロガー構成を上書きする方法の例を次に示します。外部構成ファイルは必要ありません..
FileLoggerTest.java:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class FileLoggerTest {
public static void main(String[] args) {
try {
String h = MyLogHandler.class.getCanonicalName();
StringBuilder sb = new StringBuilder();
sb.append(".level=ALL\n");
sb.append("handlers=").append(h).append('\n');
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
} catch (IOException | SecurityException ex) {
// Do something about it
}
Logger.getGlobal().severe("Global SEVERE log entry");
Logger.getLogger(FileLoggerTest.class.getName()).log(Level.SEVERE, "This is a SEVERE log entry");
Logger.getLogger("SomeName").log(Level.WARNING, "This is a WARNING log entry");
Logger.getLogger("AnotherName").log(Level.INFO, "This is an INFO log entry");
Logger.getLogger("SameName").log(Level.CONFIG, "This is an CONFIG log entry");
Logger.getLogger("SameName").log(Level.FINE, "This is an FINE log entry");
Logger.getLogger("SameName").log(Level.FINEST, "This is an FINEST log entry");
Logger.getLogger("SameName").log(Level.FINER, "This is an FINER log entry");
Logger.getLogger("SameName").log(Level.ALL, "This is an ALL log entry");
}
}
MyLogHandler.java
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
public final class MyLogHandler extends FileHandler {
public MyLogHandler() throws IOException, SecurityException {
super("/tmp/path-to-log.log");
setFormatter(new SimpleFormatter());
setLevel(Level.ALL);
}
@Override
public void publish(LogRecord record) {
System.out.println("Some additional logic");
super.publish(record);
}
}