1、可以在main方法中书写以下语句进行log。
final Logger baseLogger = Logger.getLogger("LogTest");
baseLogger.setLevel(Level.INFO);//this set the log level to info. that means you can only pring info message to log file.
final Handler[] handlers = baseLogger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
baseLogger.removeHandler(handlers[i]);
}
try {
baseLogger.addHandler(new DefaultHandler()); //class "DefaultHandler" is the default handler for log records. It currently only logs to a file in the format offered by TextFormatter.
} catch (FreeColException e) {
e.printStackTrace();
}
2、可以在配置文件(${jdk}\jar\lib下面找到logging.properties文件)里面改日志记录的级别。
3、定义"DefaultHandler" 类,用于处理日志。
public final class DefaultHandler extends Handler {
private static final String fileName = new String("test.log");
private FileWriter fileWriter;
/**
* The constructor to use.
* @throws Exception In case the log file could not be created/written to.
*/
public DefaultHandler() throws Exception {
File file = new File(fileName);
if (file.exists()) {
if (file.isDirectory()) {
throw new Exception("Log file \"" + fileName + "\" could not be created.");
} else if (file.isFile()) {
file.delete();
}
}
try {
file.createNewFile();
} catch (IOException e) {
throw new Exception("Log file \"" + fileName + "\" could not be created.");
}
if (!file.canWrite()) {
throw new Exception("Can not write in log file \"" + fileName + "\".");
}
try {
fileWriter = new FileWriter(file);
} catch (IOException e) {
throw new Exception("Can not write in log file \"" + fileName + "\".");
}
// We use TextFormatter that we build latter.
setFormatter(new TextFormatter());
try {
String str = "version: 1.0\n"
+ "Java vendor: " + System.getProperty("java.vendor") + "\n"
+ "Java version: " + System.getProperty("java.version") + "\n"
+ "Java WM name: " + System.getProperty("java.vm.name") + "\n"
+ "Java WM vendor: " + System.getProperty("java.vm.vendor") + "\n"
+ "Java WM version: " + System.getProperty("java.vm.version") + "\n\n"
+ "OS name: " + System.getProperty("os.name") + "\n"
+ "OS architecture: " + System.getProperty("os.arch") + "\n"
+ "OS version: " + System.getProperty("os.version") + "\n\n";
fileWriter.write(str, 0, str.length());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Closes this handler so that it will stop handling log records.
*/
public void close() {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Flushes the data that this handler has logged.
*/
public void flush() {
try {
fileWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Publishes the given LogRecord by writing its data to a file using
* a TextFormatter.
*
* @param record The log record to publish.
*/
public void publish(LogRecord record) {
if (record.getLevel().intValue() < getLevel().intValue()) {
return;
}
String str = getFormatter().format(record);
try {
fileWriter.write(str, 0, str.length());
} catch (IOException e) {
e.printStackTrace();
}
flush();
}
}
4、定义自己的Formatter格式。
/**
* Formats a log record's data into human-readable text.
*/
final class TextFormatter extends Formatter {
/**
* The constructor to use.
*/
public TextFormatter() {
}
/**
* Formats the given log record's data into human-readable text.
*
* @param record The log record whose data needs to be formatted.
* @return The log record's data as a string.
*/
public String format(LogRecord record) {
String level;
if (record.getLevel() == Level.INFO) {
level = "INFO";
} else if (record.getLevel() == Level.ALL) {
level = "ALL";
} else if (record.getLevel() == Level.SEVERE) {
level = "SEVERE";
} else if (record.getLevel() == Level.WARNING) {
level = "WARNING";
} else {
level = "UNKNOWN";
}
//you can build your own result format
String result = record.getSourceClassName() + ' ' + record.getSourceMethodName();
result += "\n\t" + level + ": " + record.getMessage().replaceAll("\n", "\n\t");
result += "\n\t" + new Date(record.getMillis()).toString();
result += "\n\tThread ID: " + record.getThreadID() + '\n';
return result;
}
}
5、实际应用中的使用.
public class Client {
private static final Logger logger = Logger.getLogger(Client.class.getName());
private void createDirs() {
String dir = System.getProperty("user.home");
String fileSeparator = System.getProperty("file.separator");
if (!dir.endsWith(fileSeparator)) {
dir += fileSeparator;
}
dir += "test";
File file = new File(dir);
if (file.exists() && file.isFile()) {
logger.warning("Could not create .freecol under ~ because there already exists a regular file with the same name.");
return;
} else if (!file.exists()) {
file.mkdir();
logger.info("Could not create .freecol under ~ because there already exists a regular file with the same name.");
}
}
}