Java log code example

时间:2021-08-16 05:03:11

Java log example

  1. Logrecord filter

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

].equals(; 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);
    }
  }
}