By
extending Formatter class we can provide custom formatters.
Formatter class has abstract method format(LogRecord record), which
formats the log record before publishing it to the external world.
import java.util.logging.*; public class CustomFormat extends Formatter{ @Override public String format(LogRecord record) { StringBuilder str = new StringBuilder(); str.append("Logger Name : "); str.append(record.getLoggerName() + "\n"); str.append("Level of the logger : "); str.append(record.getLevel() +"\n"); str.append("Message : "); str.append(record.getMessage() +"\n"); return str.toString(); } }
import java.io.IOException; import java.util.logging.*; public class FormatEx { static final Logger myLogger = Logger.getLogger("Simple Logger"); public static void main(String args[]) throws IOException{ Handler handler1 = new FileHandler("file1.out"); CustomFormat format = new CustomFormat(); myLogger.addHandler(handler1); myLogger.setLevel(Level.ALL); handler1.setFormatter(format); myLogger.log(Level.INFO, "Information Message"); myLogger.log(Level.WARNING, "Warning Message"); myLogger.log(Level.SEVERE, "Severe Message"); handler1.close(); } }
No comments:
Post a Comment