Java log example
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class SimpleFilter {
private static Logger logger = Logger.getLogger("SimpleFilter");
static class Duck {
};
static class Wombat {
};
static void sendLogMessages() {
logger.log(Level.WARNING, "Aduck in the house!", new Duck());
logger.log(Level.WARNING, "A Wombat at large!", newWombat());
}
public static void main(String[] args) {
sendLogMessages();
logger.setFilter(newFilter() {
public boolean isLoggable(LogRecord record){
Object[] params = record.getParameters();
if (params == null)
return true; // No parameters
if (record.getParameters()[0]instanceof Duck)
return true; // Only log Ducks
return false;
}
});
logger.info("After setting filter..");
sendLogMessages();
}
}
Output:
Aug 28,2013 11:46:04 AM SimpleFilter sendLogMessages
WARNING:A duck in the house!
Aug 28,2013 11:46:04 AM SimpleFilter sendLogMessages
WARNING:A Wombat at large!
Aug 28,2013 11:46:04 AM SimpleFilter main
INFO:After setting filter..
Aug 28,2013 11:46:04 AM SimpleFilter sendLogMessages
WARNING:A duck in the house!
注:重写isLoggable方法可以对logrecord对象进行过滤。
2. Simple for Formatter Example
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class SimpleFormatterExample {
private static Logger logger = Logger.getLogger("SimpleFormatterExample");
private static void logMessages() {
logger.info("Line One");
logger.info("Line Two");
}
public static void main(String[] args) {
logger.setUseParentHandlers(false);
Handler conHdlr = new ConsoleHandler();
conHdlr.setFormatter(new Formatter() {
public String format(LogRecord record) {
return record.getLevel() + " : "
+ record.getSourceClassName() + " -:- "
+ record.getSourceMethodName() + " -:- "
+ record.getMessage() + "\n";
}
});
logger.addHandler(conHdlr);
logMessages();
}
}
Output:
INFO : SimpleFormatterExample -:- logMessages -:- Line One
INFO : SimpleFormatterExample -:- logMessages -:- Line Two
注:可以对输出的log格式进行特定格式化。
3. Format log output by overriding tostring()function,
import java.util.logging.Level;
import java.util.logging.LogRecord;
public class PrintableLogRecord extends LogRecord {
public PrintableLogRecord(Level level, String str) {
super(level, str);
}
public StringtoString() {
String result = "Level<" + getLevel() + ">\n" + "LoggerName<"
+ getLoggerName() + ">\n" + "Message<" + getMessage() + ">\n"
+ "CurrentMillis<" + getMillis() + ">\n" + "Params";
Object[] objParams = getParameters();
if (objParams == null)
result += "<null>\n";
else
for (int i =0; i < objParams.length; i++)
result += " Param # <" + i + " value "
+ objParams[i].toString() + ">\n";
result += "ResourceBundle<" + getResourceBundle()
+ ">\nResourceBundleName<" + getResourceBundleName()
+ ">\nSequenceNumber<" + getSequenceNumber()
+ ">\nSourceClassName<" + getSourceClassName()
+ ">\nSourceMethodName<" + getSourceMethodName()
+ ">\nThreadId<" + getThreadID() + ">\nThrown<" +getThrown()
+ ">";
return result;
}
public static void main(String[] args) {
PrintableLogRecord logRecord = new PrintableLogRecord(Level.FINEST,
"SimpleLog Record");
System.out.println(logRecord);
}
}
Output:
Level<FINEST>
LoggerName<null>
Message<SimpleLog Record>
CurrentMillis<1377662640451>
Params<null>
ResourceBundle<null>
ResourceBundleName<null>
SequenceNumber<0>
SourceClassName<null>
SourceMethodName<null>
ThreadId<10>
Thrown<null>
4. email log
import java.util.logging.*;
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailLogger {
private static Logger logger = Logger.getLogger("EmailLogger");
public static void main(String[] args) throws Exception {
logger.setUseParentHandlers(false);
Handler conHdlr = new ConsoleHandler();
conHdlr.setFormatter(new Formatter() {
public String format(LogRecord record) {
return record.getLevel() + " : "
+ record.getSourceClassName() + ":"
+ record.getSourceMethodName() + ":"
+ record.getMessage() + "\n";
}
});
logger.addHandler(conHdlr);
logger.addHandler(
new FileHandler("EmailLoggerOutput.xml"));
logger.addHandler(new MailingHandler());
logger.log(Level.INFO,
"Testing Multiple Handlers", "SendMailTrue");
}
}
// A handler that sends mail messages
class MailingHandler extends Handler {
public void publish(LogRecord record) {
Object[] params = record.getParameters();
if(params == null) return;
// Send mail only if the parameter is true
if(params[0].equals("SendMailTrue")) {
new MailInfo("[email protected]",
new String[] { "[email protected]" },
"smtp.theunixman.com", "Test Subject",
"Test Content").sendMail();
}
}
public void close() {}
public void flush() {}
}
class MailInfo {
private String fromAddr;
private String[] toAddr;
private String serverAddr;
private String subject;
private String message;
public MailInfo(String from, String[] to,
String server, String subject, String message) {
fromAddr = from;
toAddr = to;
serverAddr = server;
this.subject = subject;
this.message = message;
}
public void sendMail() {
try {
Properties prop = new Properties();
prop.put("mail.smtp.host", serverAddr);
Session session =
Session.getDefaultInstance(prop, null);
session.setDebug(true);
// Create a message
Message mimeMsg = new MimeMessage(session);
// Set the from and to address
Address addressFrom = new InternetAddress(fromAddr);
mimeMsg.setFrom(addressFrom);
Address[] to = new InternetAddress[toAddr.length];
for(int i = 0; i < toAddr.length; i++)
to[i] = new InternetAddress(toAddr[i]);
mimeMsg.setRecipients(Message.RecipientType.TO,to);
mimeMsg.setSubject(subject);
mimeMsg.setText(message);
Transport.send(mimeMsg);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}