Reprinted: http://whotodo.iteye.com/blog/1701596
In the object-oriented world, we can anthropomorphic objects. They not only possess resources (data), but also implement some functions (methods ). Logger is built in Java. Android also supports a log recorder that can write log information to the console or file.
package org.vhow.android; import java.io.IOException; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; public class AppMain { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger whose name is "AppMain" Logger aLogger = Logger.getLogger(AppMain.class.getName()); // This Logger object will records all kinds of logs. aLogger.setLevel(Level.ALL); // Write logging message to Console. sentLogMessageToConsole(aLogger); // Writer logging message to a File. sentLogMessageToFile(aLogger); // Log a message. aLogger.log(Level.INFO, "info"); } private static void sentLogMessageToConsole(Logger aLogger) { // A ConsoleHandler object can publish records to System.err. ConsoleHandler aConsoleHandler = new ConsoleHandler(); // All kinds of logs will be logged by this handler. aConsoleHandler.setLevel(Level.ALL); // Format LogRecords for this Handler. aConsoleHandler.setFormatter(new LogRecordFormatter()); // Add the ConsoleHanler object to receive the logging messages. aLogger.addHandler(aConsoleHandler); } private static void sentLogMessageToFile(Logger aLogger) throws IOException { // A FileHandler object can writer log message to a file. FileHandler aFileHandler = new FileHandler("logs.log"); // All kinds of logs will be logged by this handler aFileHandler.setLevel(Level.ALL); // / Add the FileHandler object to receive the logging messages. aLogger.addHandler(aFileHandler); } }
We also need a class that defines the log record format.
package org.vhow.android; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogRecord; class LogRecordFormatter extends Formatter { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date; @Override public String format(LogRecord record) { date = new Date(record.getMillis()); return dateFormat.format(date) + ", " + record.getSourceClassName() + ", " + record.getSourceMethodName() + ", " + record.getLevel() + ": " + record.getMessage() + "\n"; } }
If the format of log information is not specified, the default log format for logging to the console is as follows:
By default, the log format written to the file is as follows: