Java by API/java.util.logging/FileHandler
FileHandler: close()
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class Main {
public static void main(String args[]) throws Exception {
LogManager lm = LogManager.getLogManager();
Logger logger;
FileHandler fh = new FileHandler("log_test.txt");
logger = Logger.getLogger("LoggingExample1");
lm.addLogger(logger);
logger.setLevel(Level.INFO);
fh.setFormatter(new XMLFormatter());
logger.addHandler(fh);
//logger.setUseParentHandlers(false);
logger.log(Level.INFO, "test 1");
logger.log(Level.INFO, "test 2");
logger.log(Level.INFO, "test 3");
fh.close();
}
}
FileHandler: publish(LogRecord record)
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.XMLFormatter;
public class Main {
public static void main(String args[]) throws Exception{
XMLFormatter formatter = new XMLFormatter();
LogRecord record = new LogRecord(Level.INFO, "XML message..");
FileHandler handler = new FileHandler("newxml.xml");
handler.setFormatter(formatter);
handler.publish(record);
handler.flush();
}
}
new FileHandler(String pattern)
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class MainClass {
public static void main(String args[]) {
Logger logger = Logger.getLogger("my.log");
Handler handler = null;
try {
handler = new FileHandler("messages.log");
} catch (IOException e) {
System.out.println("Could not create file. Using the console handler");
handler = new ConsoleHandler();
}
logger.addHandler(handler);
handler.setFormatter(new XMLFormatter());
logger.info("Our first logging message");
logger.severe("Something terrible happened");
}
}