Java/Language Basics/Log — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:47, 1 июня 2010

Содержание

A file handler that appends.

   
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    boolean append = true;
    FileHandler handler = new FileHandler("my.log", append);
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(handler);
  }
}





Alternate XML by using FileHandler

   
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileHandler handler = new FileHandler("alterxml.xml");
    Logger logger = Logger.getLogger("your.logging");
    logger.addHandler(handler);
    logger.log(Level.INFO, "alternative xml");
  }
}





An example of a program providing the functionality of logging

   
import java.util.logging.Logger;
public class Main{
  public static void main(String[] args) {
    Logger log = Logger.getLogger("com.mycompany.BasicLogging");
    log.severe("severe message");
    log.warning("warning message");
    log.info("info message");
    log.config("config message");
    log.fine("fine level one message");
    log.finer("fine level two message");
    log.finest("fine level three message");
  }
}





A simple wrapper around JDK logging facilities

 
/***
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *    Project: www.simpledbm.org
 *    Author : Dibyendu Majumdar
 *    Email  : dibyendu@mazumdar.demon.co.uk
 */
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
/**
 * A simple wrapper around JDK logging facilities. The aim is to allow 
 * easy switch to another logging system, such as Log4J.
 * 
 * @author Dibyendu Majumdar
 */
public final class Logger {
  
  /**
   * Instance of the real logger object.
   */
  private final java.util.logging.Logger realLogger;
  
  /**
   * Obtain a new or existing Logger instance. 
   * @param name Name of the logger, package names are recommended
   */
  public static Logger getLogger(String name) {
    return new Logger(name);
  }
  
  public static void configure(String filename) {
    FileInputStream is = null; 
    try {
      is = new FileInputStream(filename);
      LogManager.getLogManager().readConfiguration(is);
    }
    catch (Exception e) {
      System.err.println("SIMPLEDBM-ERROR: Failed to initialize logging system due to following error: " + e.getMessage());
      e.printStackTrace();
    }
    finally {
      try {
        is.close();
      } catch (IOException e) {}
    }
  }
  
  public Logger(String name) {
    realLogger = java.util.logging.Logger.getLogger(name);
  }
  
  public void info(String sourceClass, String sourceMethod, String message) {
    realLogger.logp(Level.INFO, sourceClass, sourceMethod, message);
  }
  
  public void info(String sourceClass, String sourceMethod, String message, Throwable thrown) {
    realLogger.logp(Level.INFO, sourceClass, sourceMethod, message, thrown);
  }
  
  public void debug(String sourceClass, String sourceMethod, String message) {
    realLogger.logp(Level.FINE, sourceClass, sourceMethod, message);
  }
  
  public void debug(String sourceClass, String sourceMethod, String message, Throwable thrown) {
    realLogger.logp(Level.FINE, sourceClass, sourceMethod, message, thrown);
  }
  public void trace(String sourceClass, String sourceMethod, String message) {
    realLogger.logp(Level.FINER, sourceClass, sourceMethod, message);
  }
  
  public void trace(String sourceClass, String sourceMethod, String message, Throwable thrown) {
    realLogger.logp(Level.FINER, sourceClass, sourceMethod, message, thrown);
  }
  
  public void warn(String sourceClass, String sourceMethod, String message) {
    realLogger.logp(Level.WARNING, sourceClass, sourceMethod, message);
  }
  
  public void warn(String sourceClass, String sourceMethod, String message, Throwable thrown) {
    realLogger.logp(Level.WARNING, sourceClass, sourceMethod, message, thrown);
  }
  public void error(String sourceClass, String sourceMethod, String message) {
    realLogger.logp(Level.SEVERE, sourceClass, sourceMethod, message);
  }
  public void error(String sourceClass, String sourceMethod, String message, Throwable thrown) {
    realLogger.logp(Level.SEVERE, sourceClass, sourceMethod, message, thrown);
  }
  
  public boolean isTraceEnabled() {
    return realLogger.isLoggable(Level.FINER);
  }
  public boolean isDebugEnabled() {
    return realLogger.isLoggable(Level.FINE);
  }
  
  public void enableDebug() {
    realLogger.setLevel(Level.FINE);
  }
  public void disableDebug() {
    realLogger.setLevel(Level.INFO);
  }
}





Basic Logging Example

  
import java.util.logging.*;
public class BasicLoggingExample {
    public static void main(String args[])
    {
        Logger logger = Logger.getLogger("BasicLoggingExample");
        logger.log(Level.INFO, "Test of logging system");
    }
}





Comparing Log Levels: To compare the severity of two logging levels, use Level.intValue().

   
import java.util.logging.Level;
public class Main {
  public static void main(String[] argv) throws Exception {
    Level level1 = Level.INFO;
    Level level2 = Level.CONFIG;
    if (level1.intValue() > level2.intValue()) {
      System.out.println("level1 is more severe");
    } else if (level1.intValue() < level2.intValue()) {
      System.out.println("level2 is more severe");
    } else {
      System.out.println("level1 == level2");
    }
  }
}





Config Demo

   
import java.util.logging.Logger;
import java.util.logging.SocketHandler;
public class Main {
  public static void main(String args[])throws Exception {
    Logger logger = Logger.getLogger("logging");
    logger.addHandler(new SocketHandler());
    logger.warning("SocketHandler is working...");
  }
}





config.properties

   

#define the logger level
your.logging.level=INFO





Configure Logging

  
// : c15:ConfigureLogging.java
//{JVMArgs: -Djava.util.logging.config.file=log.prop}
//{Clean: java0.log,java0.log.lck}
//From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
//www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.logging.Logger;
public class ConfigureLogging {
  static Logger lgr = Logger.getLogger("com"), lgr2 = Logger
      .getLogger("com.bruceeckel"), util = Logger
      .getLogger("com.bruceeckel.util"), test = Logger
      .getLogger("com.bruceeckel.test"), rand = Logger
      .getLogger("random");
  public ConfigureLogging() {
    /*
     * Set Additional formatters, Filters and Handlers for the loggers here.
     * You cannot specify the Handlers for loggers except the root logger
     * from the configuration file.
     */
  }
  public static void main(String[] args) {
    sendLogMessages(lgr);
    sendLogMessages(lgr2);
    sendLogMessages(util);
    sendLogMessages(test);
    sendLogMessages(rand);
  }
  private static void sendLogMessages(Logger logger) {
    System.out.println(" Logger Name : " + logger.getName() + " Level: "
        + logger.getLevel());
    logger.finest("Finest");
    logger.finer("Finer");
    logger.fine("Fine");
    logger.config("Config");
    logger.info("Info");
    logger.warning("Warning");
    logger.severe("Severe");
  }
} ///:~





Configuring Logger Default Values with a Properties File

   
# The following creates two handlers
handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler
    
# Set the default logging level for the root logger
.level = ALL
    
# Set the default logging level for new ConsoleHandler instances
java.util.logging.ConsoleHandler.level = INFO
    
# Set the default logging level for new FileHandler instances
java.util.logging.FileHandler.level = ALL
    
# Set the default formatter for new ConsoleHandler instances
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
    
# Set the default logging level for the logger named com.mycompany
com.mycompany.level = ALL
The custom logging properties file is loaded by specifying a system property on the command line:
java -Djava.util.logging.config.file=mylogging.properties <class>





Create a memory handler with a memory of 100 records and dumps the records into the file my.log

   
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileHandler fhandler = new FileHandler("my.log");
    int numRec = 100;
    MemoryHandler mhandler = new MemoryHandler(fhandler, numRec, Level.OFF) {
      public synchronized void publish(LogRecord record) {
        super.publish(record);
        push();
      }
    };
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(mhandler);
  }
}





Create log with package name

   
import org.apache.log4j.*;
public class SimpleLogging {
    public static void main(String[] args) {
        Logger logger = Logger.getLogger(SimpleLogging.class.getPackage().getName());
        logger.info("Hello this is an info message");
    }
}





Creating a Custom Formatter for a Logger Handler

   
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
class MyHtmlFormatter extends Formatter {
  public String format(LogRecord rec) {
    StringBuffer buf = new StringBuffer(1000);
    if (rec.getLevel().intValue() >= Level.WARNING.intValue()) {
      buf.append("<b>");
      buf.append(rec.getLevel());
      buf.append("</b>");
    } else {
      buf.append(rec.getLevel());
    }
    buf.append(" ");
    buf.append(rec.getMillis());
    buf.append(" ");
    buf.append(formatMessage(rec));
    buf.append("\n");
    return buf.toString();
  }
  public String getHead(Handler h) {
    return "<HTML><HEAD>" + (new Date()) + "</HEAD><BODY><PRE>\n";
  }
  public String getTail(Handler h) {
    return "</PRE></BODY></HTML>\n";
  }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    Logger logger = Logger.getLogger("com.mycompany");
    FileHandler fh = new FileHandler("mylog.html");
    fh.setFormatter(new MyHtmlFormatter());
    logger.addHandler(fh);
    logger.setLevel(Level.ALL);
    logger.severe("my severe message");
    logger.info("my info message");
    logger.entering("Main class", "myMethod", new Object[] { "para1", "para2" });
  }
}





Creating a Custom Log Level

   
import java.util.logging.Level;
import java.util.logging.Logger;
class MyLevel extends Level {
  public static final Level DISASTER = new MyLevel("DISASTER", Level.SEVERE.intValue() + 1);
  public MyLevel(String name, int value) {
    super(name, value);
  }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    Logger logger = Logger.getLogger("com.mycompany");
    logger.log(MyLevel.DISASTER, "my disaster message");
    Level disaster = Level.parse("DISASTER");
    logger.log(disaster, "my disaster message");
  }
}





Custom filter

   
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
class Person {
  private String name = null;
  private int age;
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getName() {
    return name;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public int getAge() {
    return age;
  }
}
class AgeFilter implements Filter {
  public boolean isLoggable(LogRecord record) {
    boolean result = false;
    Object[] objs = record.getParameters();
    Person person = (Person) objs[0];
    if (person != null) {
      int age = person.getAge();
      if (age > 30)
        result = true;
      else
        result = false;
    }
    return result;
  }
}
public class Main {
  public static void main(String args[]) {
    Logger logger = Logger.getLogger("your.logging");
    AgeFilter filter = new AgeFilter();
    logger.setFilter(filter);
    Person person = new Person("YourName", 32);
    logger.log(Level.INFO, "Person has age " + person.getAge(), person);
  }
}





#define the properties for the SocketHandler

   
java.util.logging.SocketHandler.level=INFO
java.util.logging.SocketHandler.host=localhost
java.util.logging.SocketHandler.port=2020





Define your own Custom Formatter

   
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public class CustomFormatter extends Formatter {
  public synchronized String format(LogRecord record) {
    String methodName = record.getSourceMethodName();
    String message = record.getMessage();
    StringBuffer buffer = new StringBuffer(50);
    buffer.append(methodName);
    buffer.append("=");
    buffer.append(message);
    return buffer.toString();
  }
}





Determining If a Message Will Be Logged

   
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    Logger logger = Logger.getLogger("com.mycompany.MyClass");
    // Check if the message will be logged
    if (logger.isLoggable(Level.FINEST)) {
      logger.finest("my finest message");
    }
  }
}





Determining When the Logging Configuration Properties are Reread

   

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.logging.LogManager;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Register for the event
    LogManager.getLogManager().addPropertyChangeListener(new PropertyChangeListener() {
      // This method is called when configuration file is reread
      public void propertyChange(PropertyChangeEvent evt) {
        String propName = evt.getPropertyName();
        Object oldValue = evt.getOldValue();
        Object newValue = evt.getOldValue();
        // All values are null
      }
    });
  }
}





Email Logger

  
//: c15:EmailLogger.java
// {RunByHand} Must be connected to the Internet
// {Depends: mail.jar,activation.jar}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
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("bruce@theunixman.ru",
        new String[] { "bruce@theunixman.ru" },
        "smtp.theunixman.ru", "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);
    }
  }
} ///:~





File Logger

  
/*
Software Architecture Design Patterns in Java
by Partha Kuchana 
Auerbach Publications
*/

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileLogger {
  public synchronized void log(String msg) {
    DataOutputStream dos = null;
    try {
      dos = new DataOutputStream(new FileOutputStream("log.txt", true));
      dos.writeBytes(msg);
      dos.close();
    } catch (FileNotFoundException ex) {
      //
    } catch (IOException ex) {
      //
    }
  }
}





Flush File Handler and Logger

   

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] args) throws Exception {
    FileHandler handler = null;
    Logger logger = Logger.getLogger("logging");
    handler = new FileHandler("pattern", 1000, 2);
    logger.addHandler(handler);
    LogRecord record = new LogRecord(Level.INFO, "Logged in a file...");
    logger.log(record);
    handler.flush();
    handler.close();
  }
}





Handling Errors While Parsing an XML File

   
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    builder.setErrorHandler(new MyErrorHandler());
    Document doc = builder.parse(new File("infilename.xml"));
  }
}
class MyErrorHandler implements ErrorHandler {
  public void error(SAXParseException e) {
    log(Level.SEVERE, "Error", e);
  }
  public void fatalError(SAXParseException e) {
    log(Level.SEVERE, "Fatal Error", e);
  }
  public void warning(SAXParseException e) {
    log(Level.WARNING, "Warning", e);
  }
  private Logger logger = Logger.getLogger("com.mycompany");
  private void log(Level level, String message, SAXParseException e) {
    int line = e.getLineNumber();
    int col = e.getColumnNumber();
    String publicId = e.getPublicId();
    String systemId = e.getSystemId();
    message = message + ": " + e.getMessage() + ": line=" + line + ", col=" + col + ", PUBLIC="
        + publicId + ", SYSTEM=" + systemId;
    logger.log(level, message);
  }
}





How to write custom Log handler

  
// : c15:CustomHandler.java
//How to write custom handler
//From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
//www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class CustomHandler {
  private static Logger logger = Logger.getLogger("CustomHandler");
  private static List strHolder = new ArrayList();
  public static void main(String[] args) {
    logger.addHandler(new Handler() {
      public void publish(LogRecord logRecord) {
        strHolder.add(logRecord.getLevel() + ":");
        strHolder.add(logRecord.getSourceClassName() + ":");
        strHolder.add(logRecord.getSourceMethodName() + ":");
        strHolder.add("<" + logRecord.getMessage() + ">");
        strHolder.add("\n");
      }
      public void flush() {
      }
      public void close() {
      }
    });
    logger.warning("Logging Warning");
    logger.info("Logging Info");
    System.out.print(strHolder);
  }
} ///:~





Java log: alternate XML log

  
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AlternateXML {
  public static void main(String args[]) {
    try {
      FileHandler handler = new FileHandler("alterxml.xml");
      Logger logger = Logger.getLogger("jexp.logging");
      logger.addHandler(handler);
      logger.log(Level.INFO, "alternative xml");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}





Java Log:Basic Logging

  
import java.util.logging.*;
import java.io.*;
public class BasicLogging {
    private static Logger logger = Logger.getLogger("MyLogger");
    private ConsoleHandler console = null;
    private FileHandler file = null;
    public BasicLogging()
    {
        console = new ConsoleHandler();
        try{
            file = new FileHandler("basicLogging.out");
        }catch(IOException ioe){
            logger.warning("Could not create a file...");
        }
        logger.addHandler(console);
        logger.addHandler(file);
    }
    public void logMessage()
    {
      logger.info("I am logging test message..");
    }
  public static void main(String args[])
  {
      BasicLogging demo = new BasicLogging();
      demo.logMessage();
  }
}





Java log: Basic logging 2

  
import java.util.logging.Logger;
public class BasicLogging1 {
  public static void main(String args[]) {
    Logger logger = Logger.getLogger("current.package");
    logger.info("Simple formatted message..");
  }
}





Java log: Custom XML Formatter

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
import java.util.logging.*;
import java.io.*;
class CustomFormatter extends Formatter
{
  public CustomFormatter(){}
   /**
     This method formats the given log record, in a java properties file style
   */
  public synchronized String format(LogRecord record)
  {
    String methodName = record.getSourceMethodName();
    String message = record.getMessage();
    StringBuffer buffer = new StringBuffer(50);
    buffer.append(methodName);
    buffer.append("=");
    buffer.append(message);
    return buffer.toString();
  }
}
public class CustomFormatterTest{
    private static Logger logger = Logger.getLogger("sam.logging");
    private String fileName = null;
    public CustomFormatterTest(String fileName)
    {
        this.fileName = fileName;
        try
        {
            FileHandler fh = new FileHandler(fileName);
            CustomFormatter formatter = new CustomFormatter();
            fh.setFormatter(formatter);
            logger.addHandler(fh);
        }catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
    }
    /**
     * This method performs the logging activity
     */
    public void logMessage()
    {
        logger.info("log this message");
    }
    public static void main(String args[]) {
        CustomFormatterTest test = new CustomFormatterTest("name");
        test.logMessage();
    }
}





Java log: File Handler Demo

  
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class FileHandlerDemo {
  private FileHandler handler = null;
  private static Logger logger = Logger.getLogger("sam.logging");
  public FileHandlerDemo(String pattern) {
    try {
      handler = new FileHandler(pattern, 1000, 2);
      logger.addHandler(handler);
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
  public void logMessage() {
    LogRecord record = new LogRecord(Level.INFO, "Logged in a file..22.");
    logger.log(record);
    handler.flush();
    handler.close();
  }
  public static void main(String[] args) {
    FileHandlerDemo demo = new FileHandlerDemo("%h/log%g.out");
    demo.logMessage();
  }
}





Java log: Hierarchy logging

  
import java.util.logging.*;
class ParentLogger{
  private Logger logger = Logger.getLogger("sam.logging");
  private Level level = null;
  
  public ParentLogger(){
    level = Level.SEVERE;
    logger.setLevel(level);
  }
  public void aMethod()
  {
    logger.log(level, "Severe message from Parent Logger");
  }
}
class ChildLogger{
    private Logger logger = Logger.getLogger("sam.logging.child");
    private Level level = null;
    public ChildLogger()
    {
        //level = Level.INFO;
        //setting the level of this child logger, if not specified, it
        // will use the level of the parent logger
        logger.setLevel(level);
    }
    public void aMethod()
    {
        logger.log(Level.INFO, "Info message from Child Logger");
        logger.log(Level.SEVERE, "Severe message from Child Logger");
    }
}

public class LoggingMonitor {
    public static void main(String[] args){
        ParentLogger pLogger = new ParentLogger();
        ChildLogger cLogger = new ChildLogger();
        cLogger.aMethod();
    }
}





Java log: Localize Logging

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
import java.util.logging.*;
import java.io.*;
import java.util.ResourceBundle;
public class LocalizeLogging
{
    private static Logger logger = Logger.getLogger("sam.logging");
    private String rbName = null;
    public LocalizeLogging(String rbName)
    {
        this.rbName = rbName;
    }
    public void logMessage()
    {
        logger.logrb(Level.INFO, "LocalizeLogging", "logMessage", rbName,"success");
    }
    public static void main(String args[]) {
        //collect the name of the resource bundle
        String rbName = "name";
        LocalizeLogging lLogging = new LocalizeLogging(rbName);
        lLogging.logMessage();
    }
}





Java log: Log and Window(JFrame, frame)

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
import java.util.logging.*;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
class LogWindow extends JFrame {
  private int width;
  private int height;
  private JTextArea textArea = null;
  private JScrollPane pane = null;
  public LogWindow(String title, int width, int height) {
    super(title);
    setSize(width, height);
    textArea = new JTextArea();
    pane = new JScrollPane(textArea);
    getContentPane().add(pane);
    setVisible(true);
  }
  /**
   * This method appends the data to the text area.
   * 
   * @param data
   *            the Logging information data
   */
  public void showInfo(String data) {
    textArea.append(data);
    this.getContentPane().validate();
  }
}
class WindowHandler extends Handler {
  //the window to which the logging is done
  private LogWindow window = null;
  private Formatter formatter = null;
  private Level level = null;
  //the singleton instance
  private static WindowHandler handler = null;
  /**
   * private constructor, preventing initialization
   */
  private WindowHandler() {
    configure();
    if (window == null)
      window = new LogWindow("Logging window", 500, 200);
  }
  /**
   * The getInstance method returns the singleton instance of the
   * WindowHandler object It is synchronized to prevent two threads trying to
   * create an instance simultaneously. @ return WindowHandler object
   */
  public static synchronized WindowHandler getInstance() {
    if (handler == null) {
      handler = new WindowHandler();
    }
    return handler;
  }
  /**
   * This method loads the configuration properties from the JDK level
   * configuration file with the help of the LogManager class. It then sets
   * its level, filter and formatter properties.
   */
  private void configure() {
    LogManager manager = LogManager.getLogManager();
    String className = this.getClass().getName();
    String level = manager.getProperty(className + ".level");
    String filter = manager.getProperty(className + ".filter");
    String formatter = manager.getProperty(className + ".formatter");
    //accessing super class methods to set the parameters
    setLevel(level != null ? Level.parse(level) : Level.INFO);
    setFilter(makeFilter(filter));
    setFormatter(makeFormatter(formatter));
  }
  /**
   * private method constructing a Filter object with the filter name.
   * 
   * @param filterName
   *            the name of the filter
   * @return the Filter object
   */
  private Filter makeFilter(String filterName) {
    Class c = null;
    Filter f = null;
    try {
      c = Class.forName(filterName);
      f = (Filter) c.newInstance();
    } catch (Exception e) {
      System.out.println("There was a problem to load the filter class: "
          + filterName);
    }
    return f;
  }
  /**
   * private method creating a Formatter object with the formatter name. If no
   * name is specified, it returns a SimpleFormatter object
   * 
   * @param formatterName
   *            the name of the formatter
   * @return Formatter object
   */
  private Formatter makeFormatter(String formatterName) {
    Class c = null;
    Formatter f = null;
    try {
      c = Class.forName(formatterName);
      f = (Formatter) c.newInstance();
    } catch (Exception e) {
      f = new SimpleFormatter();
    }
    return f;
  }
  /**
   * This is the overridden publish method of the abstract super class
   * Handler. This method writes the logging information to the associated
   * Java window. This method is synchronized to make it thread-safe. In case
   * there is a problem, it reports the problem with the ErrorManager, only
   * once and silently ignores the others.
   * 
   * @record the LogRecord object
   *  
   */
  public synchronized void publish(LogRecord record) {
    String message = null;
    //check if the record is loggable
    if (!isLoggable(record))
      return;
    try {
      message = getFormatter().format(record);
    } catch (Exception e) {
      reportError(null, e, ErrorManager.FORMAT_FAILURE);
    }
    try {
      window.showInfo(message);
    } catch (Exception ex) {
      reportError(null, ex, ErrorManager.WRITE_FAILURE);
    }
  }
  public void close() {
  }
  public void flush() {
  }
}
public class CustomHandlerDemo {
  private WindowHandler handler = null;
  private Logger logger = null;
  public CustomHandlerDemo() {
    handler = WindowHandler.getInstance();
    //obtaining a logger instance and setting the handler
    logger = Logger.getLogger("sam.logging.handler");
    logger.addHandler(handler);
  }
  /**
   * This method publishes the log message
   */
  public void logMessage() {
    logger.info("Hello from WindowHandler...");
  }
  public static void main(String args[]) {
    //logging with the help of a logger
    CustomHandlerDemo demo = new CustomHandlerDemo();
    demo.logMessage();
    //using the handler.publish() to log
    WindowHandler h = WindowHandler.getInstance();
    LogRecord r = new LogRecord(Level.WARNING,
        "The Handler publish method...");
    h.publish(r);
  }
}





Java log: log filter

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
import java.util.logging.*;
public class FilterDemo
{
  private Logger logger = null;
  private AgeFilter filter = null;
  public FilterDemo()
  {
    //obtaining a logger object
    logger = Logger.getLogger("sam.logging");
    //creating a AgeFilter object
    filter = new AgeFilter();
    //attaching the filter to the logger
    logger.setFilter(filter);
  }
  /**
   * This method logs the message
   */
  public void logMessage(Person person)
  {
    //logging the message with Person object as parameter
    logger.log(Level.INFO, "Person has age "+person.getAge(), person);
  }
  public static void main(String args[])
  {
    FilterDemo demo = new FilterDemo();
    //creating Person objects
    Person person1 = new Person("Paul", 32);
    Person person2 = new Person("sam", 29);
    //logging with each Person object
    demo.logMessage(person1);
    demo.logMessage(person2);
  }
}
class Person{
  private String name = null;
  private int age;
  public Person(String name, int age)
  {
   this.name = name;
   this.age = age;
  }
  public void setName(String name)
  {
   this.name = name;
  }
  public String getName()
  {
   return name;
  }
  public void setAge(int age)
  {
   this.age = age;
  }
  public int getAge()
  {
   return age;
  }
}
class AgeFilter implements Filter {
    public AgeFilter() {
    }
    /**
     * This is the overridden method from the Filter interface.
     * It checks the Person object associated with the LogRecord
     * checks the age>30, and returns true
     *@param record the LogRecord object
     *@return boolean true/false
     */
    public boolean isLoggable(LogRecord record) {
        boolean result = false;
        //obtaining the Person object from the record
        Object[] objs = record.getParameters();
        Person person = (Person)objs[0];
        //check if person is not null
        if(person !=null) {
            //obtain the age
            int age = person.getAge();
            if(age>30)
                result = true;
            else
                result = false;
        }
        return result;
    }
}





Java log: Logging Server

  
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class LoggingServer {
  private ServerSocket serverSocket = null;
  private Socket socket = null;
  public LoggingServer(int port) {
    try {
      serverSocket = new ServerSocket(port);
      socket = serverSocket.accept();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
  public void acceptMessage() {
    try {
      InputStream inStream = socket.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
      String str = null;
      while ((str = reader.readLine()) != null) {
        System.out.println(str);
      }
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
  public static void main(String args[]) {
    LoggingServer server = new LoggingServer(2020);
    server.acceptMessage();
  }
}





Java log: Memory Handler Demo

  
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
public class MemoryHandlerDemo {
  private ConsoleHandler handler = null;
  private MemoryHandler mHandler = null;
  private static Logger logger = Logger.getLogger("sam.logging");
  public MemoryHandlerDemo(int size, Level pushLevel) {
    handler = new ConsoleHandler();
    mHandler = new MemoryHandler(handler, size, pushLevel);
    logger.addHandler(mHandler);
    logger.setUseParentHandlers(false);
  }
  public void logMessage() {
    LogRecord record1 = new LogRecord(Level.SEVERE, "This is SEVERE level message");
    LogRecord record2 = new LogRecord(Level.WARNING, "This is WARNING level message");
    logger.log(record1);
    logger.log(record2);
  }
  public static void main(String args[]) {
    MemoryHandlerDemo demo = new MemoryHandlerDemo(2, Level.SEVERE);
    demo.logMessage();
  }
}





Java log: Remote Config Reader

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
//
/*
If this property is not passed to the logging framework at startup, 
by default, LogManager reads a configuration file located in the 
"JAVA_HOME/jre/lib/ logging.properties" file. This configuration 
file defines the default configuration parameters for the logging
framework to work. It is possible to override the default location 
and specify our own configuration file by passing a command line 
option to the Java runtime as:
java -Djava.util.logging.config.file=configuration file name
 RemoteConfigReader.java
*/
import java.util.logging.LogManager;
import java.net.URL;
import java.net.URLConnection;
import java.net.MalformedURLException;
import java.io.InputStream;
import java.io.IOException;
public class RemoteConfigReader
{
 private String urlString = "http://www.xyz.ru/config.properties";
 private URL url = null;
 private URLConnection urlConn = null;
 private InputStream inStream = null;
 private LogManager manager = null;
 /**
  * The constructor obtains a connection to the URL specified in the
  * urlString object, obtains an InputStream on the URL and
  * calls the readConfiguration(InputStream) of the LogManager class
  * to perform the initialization
  */
 public RemoteConfigReader(){
      try{
           url = new URL(urlString);
           urlConn = url.openConnection();
           inStream = urlConn.getInputStream();
           manager = LogManager.getLogManager();
           manager.readConfiguration(inStream);
      }catch(MalformedURLException mue){
           System.out.println("could not open url: "+urlString);
      }catch(IOException ioe){
           System.out.println("IOException occured in reading: "+urlString);
      }catch(SecurityException se){
           System.out.println("Security exception occured in class RemoteConfigLoader");
      }
 }
}





Java log: Socket Handler Demo

  
import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.SocketHandler;
public class SocketHandlerDemo {
  private SocketHandler handler = null;
  private static Logger logger = Logger.getLogger("sam.logging");
  public SocketHandlerDemo(String host, int port) {
    try {
      handler = new SocketHandler(host, port);
      logger.addHandler(handler);
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
  public void logMessage() {
    logger.warning("SocketHandler is working...");
  }
  public static void main(String args[]) {
    SocketHandlerDemo demo = new SocketHandlerDemo("localhost", 2020);
    demo.logMessage();
  }
}





Java log: Stream Handler Demo

  
import java.io.OutputStream;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
public class StreamHandlerDemo {
  private StreamHandler handler = null;
  private OutputStream outStream = null;
  private static Logger logger = Logger.getLogger("sam.logging");
  public StreamHandlerDemo() {
    outStream = System.out;
    handler = new StreamHandler(outStream, new SimpleFormatter());
    logger.addHandler(handler);
    logger.setUseParentHandlers(false);
  }
  public void logMessage() {
    logger.info("StreamHandler is working!");
  }
  public static void main(String[] args) {
    StreamHandlerDemo demo = new StreamHandlerDemo();
    demo.logMessage();
  }
}





Java log: various log methods

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
import java.util.logging.*;
import java.io.IOException;
public class LogMethods {
    private static Logger logger = Logger.getLogger("sam.logging");
    public LogMethods()
    {
        //first obtain the logmanager instance
        LogManager manager = LogManager.getLogManager();
        //remove all the associated handlers with this manager
        manager.reset();
        //create a new handler for the logger to write messages
        // to the console
        ConsoleHandler ch = new ConsoleHandler();
        ch.setLevel(Level.FINEST);
        //setting the logger level and handler
        logger.setLevel(Level.FINEST);
        logger.addHandler(ch);
    }
    /**
     * This method demonstrates the basic logging methods
     */
    public void printBasicMethods()
    {
        logger.log(Level.INFO, "THIS IS INFO LEVEL MESSAGE");
        //creating a log record on our own
        LogRecord record = new LogRecord(Level.SEVERE, "OUR OWN LOGRECORD OBJECT");
        //logging the log record object
        logger.log(record);
    }
    /**
     * This method demonstrates the precise logging methods
     */
    public void printPreciseMethods()
    {
        logger.logp(Level.INFO, "LogMethods", "printPreciseMethods","PRECISE METHODS..");
    }
    /**
     * This method demonstrates the level based logging methods
     */
    public void printLevelMethods()
    {
        logger.fine("THIS IS A FINE LEVEL MESSAGE");
        logger.finer("THIS IS A FINER LEVEL MESSAGE");
        logger.finest("THIS IS A FINEST LEVEL MESSAGE");
        logger.config("THIS IS CONFIG LEVEL MESSAGE");
    }
    /**
     *This method demonstrates the method level logging methods
     */
    public void printMethod()
    {
        logger.entering("LogMethods", "printMethod");
        logger.exiting("LogMethods", "printMethod");
    }
    public static void main(String[] args)
    {
        LogMethods lm = new LogMethods();
        lm.printBasicMethods();
        lm.printPreciseMethods();
        lm.printLevelMethods();
        lm.printMethod();
    }
}





Java log: XML log

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
import java.util.logging.*;
import java.io.*;
public class XMLLogging
{
    private     ConsoleHandler ch ;
    private     XMLFormatter formatter ;
    private     FileHandler handler = null;
    /**
     * constructor
     */
    public XMLLogging() {
        ch = new ConsoleHandler();
        formatter = new XMLFormatter();
    }
    /**
     * This method demonstrates the logging using XMLFormatter
     * and should there be an exception, the exception
     * is logged into the console with ConsoleHandler and formatted
     * withXMLFormatter.
     */
    public void logMessage()
    {
        //creating a LogRecord object with level and message
        LogRecord record = new LogRecord(Level.INFO, "XML message..");
        try
        {
            //creating a StreamHandler object to file output the xml message
            handler = new FileHandler("newxml.xml");
            handler.setFormatter(formatter);
            //publishing the log message to the file and flushing the buffer
            handler.publish(record);
            handler.flush();
        }catch(Exception e) {
            //creating a log record object with the WARNING level
            //and exception message
            LogRecord rec = new LogRecord(Level.WARNING, e.toString());
            //setting the formatter for the consolehandler as
            //XMLFormatter and publishing the message
            ch.setFormatter(formatter);
            ch.publish(rec);
        }
    }
    public static void main(String args[]) {
        XMLLogging logging = new XMLLogging();
        logging.logMessage();
    }
}





Limiting the Size of a Log by Using a Rotating Sequence of Files

   
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a file handler that uses 3 logfiles, each with a limit of 1Mbyte
    String pattern = "my%g.log";
    int limit = 1000000; // 1 Mb
    int numLogFiles = 3;
    FileHandler fh = new FileHandler(pattern, limit, numLogFiles);
    // Add to logger
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(fh);
  }
}





Limiting the Size of a Log File

   
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a file handler with a limit of 1 megabytes
    String pattern = "my.log";
    int limit = 1000000; // 1 Mb
    FileHandler fh = new FileHandler("my.log", limit, 1);
    // Add to logger
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(fh);
  }
}





Localized Logging

   
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
  public static void main(String args[]) {
    Logger logger = Logger.getLogger("your.logging");
    String rbName = null;
    logger.logrb(Level.INFO, "LocalizeLogging", "logMessage", rbName, "success");
  }
}





Log Client Filter

  
import java.util.logging.LogRecord;
public class ClientFilter implements java.util.logging.Filter {
  public boolean isLoggable(LogRecord record) {
    if (record.getMessage().startsWith("client"))
      return (true);
    else
      return (false);
  }
}





Logger Demo

   
import org.apache.log4j.*;
public class LoggerDemo {
    private static Logger logger = Logger.getLogger(LoggerDemo.class.getPackage().getName());
    public LoggerDemo(String rbName) {
        logger.setAdditivity(false);
        logger.debug("A");
        logger.setResourceBundle(java.util.ResourceBundle.getBundle(rbName));
        logger.debug("B");
    }
    public void doLogging(String name) {
        logger.debug("Entered the doLogging method..");
        //do something
        
        logger.info("printing the message...");
        logger.debug("Exiting the doLogging method...");
    }
    public void doLocalizedLogging() {
        logger.l7dlog(Level.DEBUG, "Entry", null);
        logger.l7dlog(Level.DEBUG, "Exit", null);
    }
    public static void main(String args[]) {
        String name = args[0];
        String rbName = args[1];
        LoggerDemo demo = new LoggerDemo(rbName);
        demo.doLogging(name);
        demo.doLocalizedLogging();
    }
}





Logger with XMLFormatter and FileHandler

   
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class Main {
  public static void main(String[] args) throws Exception {
    Logger logger = Logger.getLogger("my.log");
    Handler handler = null;
    handler = new FileHandler("messages.log");
    logger.addHandler(handler);
    handler.setFormatter(new XMLFormatter());
    logger.info("Our first logging message");
    logger.severe("Something terrible happened");
  }
}





Logging a Method Call

   

import java.util.logging.Level;
import java.util.logging.Logger;
//package com.mycompany;
class MyClass {
  public boolean myMethod(int p1, Object p2) {
    Logger logger = Logger.getLogger("com.mycompany.MyClass");
    if (logger.isLoggable(Level.FINER)) {
      logger.entering(this.getClass().getName(), "myMethod", new Object[] { new Integer(p1), p2 });
    }
    System.out.println("Method body");
    boolean result = true;
    if (logger.isLoggable(Level.FINER)) {
      logger.exiting(this.getClass().getName(), "myMethod", new Boolean(result));
      logger.exiting(this.getClass().getName(), "myMethod");
    }
    return result;
  }
}





Logging an Exception

   
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
//package com.mycompany;
public class Main {
  public static void main(String[] argv) {
    Logger logger = Logger.getLogger("com.mycompany.MyClass");
    try {
      throw new IOException();
    } catch (Throwable e) {
      logger.log(Level.SEVERE, "Uncaught exception", e);
    }
    Exception ex = new IllegalStateException();
    logger.throwing("Main class", "myMethod", ex);
  }
}





Logging Example 1

  
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class LoggingExample1 {
  public static void main(String args[]) {
    try {
      LogManager lm = LogManager.getLogManager();
      Logger logger;
      FileHandler fh = new FileHandler("log_test.txt");
      logger = Logger.getLogger("LoggingExample1");
      lm.addLogger(logger);
      logger.setLevel(Level.INFO);
      fh.setFormatter(new XMLFormatter());
      logger.addHandler(fh);
      // root logger defaults to SimpleFormatter. We don"t want messages
      // logged twice.
      //logger.setUseParentHandlers(false);
      logger.log(Level.INFO, "test 1");
      logger.log(Level.INFO, "test 2");
      logger.log(Level.INFO, "test 3");
      fh.close();
    } catch (Exception e) {
      System.out.println("Exception thrown: " + e);
      e.printStackTrace();
    }
  }
}





Logging Level Manipulation

  
// : c15:LoggingLevelManipulation.java
//From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
//www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.logging.Level;
import java.util.logging.Logger;
public class LoggingLevelManipulation {
  
  private static Logger lgr = Logger.getLogger("com"), lgr2 = Logger
      .getLogger("com.bruceeckel"), util = Logger
      .getLogger("com.bruceeckel.util"), test = Logger
      .getLogger("com.bruceeckel.test"), rand = Logger
      .getLogger("random");
  static void printLogMessages(Logger logger) {
    logger.finest(logger.getName() + " Finest");
    logger.finer(logger.getName() + " Finer");
    logger.fine(logger.getName() + " Fine");
    logger.config(logger.getName() + " Config");
    logger.info(logger.getName() + " Info");
    logger.warning(logger.getName() + " Warning");
    logger.severe(logger.getName() + " Severe");
  }
  static void logMessages() {
    printLogMessages(lgr);
    printLogMessages(lgr2);
    printLogMessages(util);
    printLogMessages(test);
    printLogMessages(rand);
  }
  static void printLevels() {
    System.out.println(" -- printing levels -- " + lgr.getName() + " : "
        + lgr.getLevel() + " " + lgr2.getName() + " : "
        + lgr2.getLevel() + " " + util.getName() + " : "
        + util.getLevel() + " " + test.getName() + " : "
        + test.getLevel() + " " + rand.getName() + " : "
        + rand.getLevel());
  }
  public static void main(String[] args) {
    printLevels();
    lgr.setLevel(Level.SEVERE);
    printLevels();
    System.out.println("com level: SEVERE");
    logMessages();
    util.setLevel(Level.FINEST);
    test.setLevel(Level.FINEST);
    rand.setLevel(Level.FINEST);
    printLevels();
    System.out.println("individual loggers set to FINEST");
    logMessages();
    lgr.setLevel(Level.FINEST);
    printLevels();
    System.out.println("com level: FINEST");
    logMessages();
  }
} ///:~





Logging Levels

  
// : c15:LoggingLevels.java
//From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
//www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.Handler;
import java.util.logging.LogManager;
public class LoggingLevels {
  private static Logger lgr = Logger.getLogger("com"), lgr2 = Logger
      .getLogger("com.bruceeckel"), util = Logger
      .getLogger("com.bruceeckel.util"), test = Logger
      .getLogger("com.bruceeckel.test"), rand = Logger
      .getLogger("random");
  private static void logMessages() {
    lgr.info("com : info");
    lgr2.info("com.bruceeckel : info");
    util.info("util : info");
    test.severe("test : severe");
    rand.info("random : info");
  }
  public static void main(String[] args) {
    lgr.setLevel(Level.SEVERE);
    System.out.println("com level: SEVERE");
    logMessages();
    util.setLevel(Level.FINEST);
    test.setLevel(Level.FINEST);
    rand.setLevel(Level.FINEST);
    System.out.println("individual loggers set to FINEST");
    logMessages();
    lgr.setLevel(Level.SEVERE);
    System.out.println("com level: SEVERE");
    logMessages();
  }
} ///:~





Log HTML Table Formatter

  
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class HTMLTableFormatter extends java.util.logging.Formatter {
  public String format(LogRecord record) {
    return ("  <tr><td>" + record.getMillis() + "</td><td>"
        + record.getMessage() + "</td></tr>\n");
  }
  public String getHead(Handler h) {
    return ("<table border>\n  "
        + "<tr><th>Time</th><th>Log Message</th></tr>\n");
  }
  public String getTail(Handler h) {
    return ("</table>\n");
  }
}





Log level

  
// : c15:SimpleFilter.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
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, "A duck in the house!", new Duck());
    logger.log(Level.WARNING, "A Wombat at large!", new Wombat());
  }
  public static void main(String[] args) {
    sendLogMessages();
    logger.setFilter(new Filter() {
      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();
  }
} ///:~





Log multiple Handlers

  
// : c15:MultipleHandlers.java
// {Clean: MultipleHandlers.xml,MultipleHandlers.xml.lck}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class MultipleHandlers {
  private static Logger logger = Logger.getLogger("MultipleHandlers");
  public static void main(String[] args) throws Exception {
    FileHandler logFile = new FileHandler("MultipleHandlers.xml");
    logger.addHandler(logFile);
    logger.addHandler(new ConsoleHandler());
    logger.warning("Output to multiple handlers");
  }
} ///:~





Log multiple Handlers 2

  
// : c15:MultipleHandlers2.java
// {Clean: MultipleHandlers2.xml,MultipleHandlers2.xml.lck}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class MultipleHandlers2 {
  private static Logger logger = Logger.getLogger("MultipleHandlers2");
  public static void main(String[] args) throws Exception {
    FileHandler logFile = new FileHandler("MultipleHandlers2.xml");
    logger.addHandler(logFile);
    logger.addHandler(new ConsoleHandler());
    logger.setUseParentHandlers(false);
    logger.warning("Output to multiple handlers");
  }
} ///:~





Log To File with FileHandler

  
//: c15:LogToFile.java
// {Clean: LogToFile.xml,LogToFile.xml.lck}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.logging.*;
public class LogToFile {
  
  private static Logger logger = Logger.getLogger("LogToFile");
  
  public static void main(String[] args) throws Exception {
    logger.addHandler(new FileHandler("LogToFile.xml"));
    logger.info("A message logged to the file");
  }
} ///:~





Log to file with FileHandler and SimpleFomatter

  
// : c15:LogToFile2.java
// {Clean: LogToFile2.txt,LogToFile2.txt.lck}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class LogToFile2 {
  private static Logger logger = Logger.getLogger("LogToFile2");
  public static void main(String[] args) throws Exception {
    FileHandler logFile = new FileHandler("LogToFile2.txt");
    logFile.setFormatter(new SimpleFormatter());
    logger.addHandler(logFile);
    logger.info("A message logged to the file");
  }
} ///:~





Memory Handler Demo

   
 
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
public class Main {
  public static void main(String args[]) throws Exception {
    Logger logger = Logger.getLogger("your.logging");
    ConsoleHandler handler = new ConsoleHandler();
    MemoryHandler mHandler = new MemoryHandler(handler, 10, Level.ALL);
    logger.addHandler(mHandler);
    logger.setUseParentHandlers(false);
    LogRecord record1 = new LogRecord(Level.SEVERE, "This is SEVERE level message");
    LogRecord record2 = new LogRecord(Level.WARNING, "This is WARNING level message");
    logger.log(record1);
    logger.log(record2);
  }
}





Minimizing the Impact of Logging Code

   
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    int count = 123;
    Logger logger = Logger.getLogger("com.mycompany.MyClass");
    logger.finest("count: " + count);
  }
}





Override LogRecord toString()

  
// : c15:PrintableLogRecord.java
// Override LogRecord toString()
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
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 String toString() {
    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()
        + ">\nThread Id<" + getThreadID() + ">\nThrown<" + getThrown()
        + ">";
    return result;
  }
  public static void main(String[] args) {
    PrintableLogRecord logRecord = new PrintableLogRecord(Level.FINEST,
        "Simple Log Record");
    System.out.println(logRecord);
  }
} ///:~





Preventing a Logger from Forwarding Log Records to Its Parent

   
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    Logger logger = Logger.getLogger("com.mycompany");
    // Stop forwarding log records to ancestor handlers
    logger.setUseParentHandlers(false);
    // Start forwarding log records to ancestor handlers
    logger.setUseParentHandlers(true);
  }
}





Remote ConfigReader with URLConnection

   
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.LogManager;
public class Main {
  public static void main(String[] argv) throws Exception {
    URLConnection urlConn = null;
    InputStream inStream = null;
    LogManager manager = null;
    URL url = new URL("http://www.xyz.ru/config.properties");
    urlConn = url.openConnection();
    inStream = urlConn.getInputStream();
    manager = LogManager.getLogManager();
    manager.readConfiguration(inStream);
  }
}





Return a message for logging.

 
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Collection;

/**
 * General string utils
 */
public class StringUtils {
  /**
   * Return a message for logging.
   * @param prefix prefix keyword for the message
   * @param msg content of the message
   * @return a message for logging
   */
  private static String toStartupShutdownString(String prefix, String [] msg) {
    StringBuffer b = new StringBuffer(prefix);
    b.append("\n/************************************************************");
    for(String s : msg)
      b.append("\n" + prefix + s);
    b.append("\n************************************************************/");
    return b.toString();
  }
  
}





Setting a Filter on a Logger Handler

   
import java.util.logging.ConsoleHandler;
import java.util.logging.Filter;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    ConsoleHandler handler = new ConsoleHandler();
    handler.setFilter(new Filter() {
      public boolean isLoggable(LogRecord record) {
       return true;
      }
    });
    // Add the handler to a logger
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(handler);
  }
}





Setting the Formatter of a Logger Handler

   

import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class Main{
  public static void main(String[] argv) throws Exception{
    Logger logger = Logger.getLogger("com.mycompany");
    FileHandler fh = new FileHandler("mylog.txt");
    fh.setFormatter(new SimpleFormatter());
    logger.addHandler(fh);
    // fh = new FileHandler("mylog.xml");
    // fh.setFormatter(new XMLFormatter());
    // logger.addHandler(fh);
    // Log a few messages
    logger.severe("my severe message");
    logger.warning("my warning message");
    logger.info("my info message");
    logger.config("my config message");
    logger.fine("my fine message");
    logger.finer("my finer message");
    logger.finest("my finest message");
  }
}





Simple Log Formatter Example

  
// : c15:SimpleFormatterExample.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
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();
  }
} ///:~





Socket Handler Demo

   
import java.util.logging.Logger;
import java.util.logging.SocketHandler;
public class Main {
  public static void main(String args[]) throws Exception{
    SocketHandler handler = null;
    Logger logger = Logger.getLogger("your.logging");
    handler = new SocketHandler("127.0.0.1", 8080);
    logger.addHandler(handler);
    logger.warning("SocketHandler is working...");
  }
}





Stream Handler

   
import java.io.OutputStream;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
public class Main {
  public static void main(String[] args) {
    Logger logger = Logger.getLogger("logging");
    OutputStream outStream = System.out;
    StreamHandler handler = new StreamHandler(outStream, new SimpleFormatter());
    logger.addHandler(handler);
    logger.setUseParentHandlers(false);
    logger.info("StreamHandler is working�");
  }
}





The Patterns in FileHandler

   
Expression       Meaning
/                The path separator of the local OS
%t               A directory suitable for storing temporary logging files, such as the temp directory of the OS
%h               A directory such as the "user.home" location, which is suitable to store user-specific data in the system
%g               A log generation number to rotate log files
%u               A number to make a log file unique to avoid any conflicts
%%               A literal percent sign





The Quintessential Logging Program

   

import java.util.logging.Logger;
//package com.mycompany;
public class Main {
  public static void main(String[] args) {
    Logger logger = Logger.getLogger("com.mycompany.BasicLogging");
    // Log a few message at different severity levels
    logger.severe("severe message");
    logger.warning("warning message");
    logger.info("info message");
    logger.config("config message");
    logger.fine("fine message");
    logger.finer("finer message");
    logger.finest("finest message");
  }
}





Use Logger with simple formatter and FileHandler

   
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class Main {
  public static void main(String[] args) throws Exception {
    Logger logger = Logger.getLogger("MyLog");
    FileHandler fh;
    fh = new FileHandler("c:\\MyLogFile.log", true);
    logger.addHandler(fh);
    logger.setLevel(Level.ALL);
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);
    logger.log(Level.WARNING, "My first log");
  }
}





Using Regular Expressions based on StreamHandler

   
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainClass {
  public static void main(String args[]) {
    Logger log = Logger.getAnonymousLogger();
    setLoggerhandler(log);
    log.finest(new Exception().toString());
  }
  public static void setLoggerhandler(Logger logger) {
    Handler handler = new ExceptionHandler();
    logger.addHandler(handler);
    logger.setLevel(Level.ALL);
  }
}
class ExceptionHandler extends StreamHandler {
  public void publish(LogRecord record) {
    String msg = record.getMessage();
    int exceptionIndex = msg.indexOf("Exception");
    if (exceptionIndex > -1) {
      Pattern pattern = Pattern.rupile("(.*Exception.*)");
      Matcher matcher = pattern.matcher(msg);
      if (matcher != null && matcher.find()) {
        String err = "EXCEPTION FOUND " + matcher.group(1);
        System.out.println(err);
      }
    }
  }
}





Window Handler: display log message in a window(JFrame)

   
 
import java.util.logging.ErrorManager;
import java.util.logging.Filter;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class LogWindow extends JFrame {
  private JTextArea textArea = new JTextArea();
  public LogWindow() {
    super("");
    setSize(300, 300);
    add(new JScrollPane(textArea));
    setVisible(true);
  }
  public void showInfo(String data) {
    textArea.append(data);
    this.validate();
  }
}
class WindowHandler extends Handler {
  private LogWindow window = null;
  private Formatter formatter = null;
  private Level level = null;
  private static WindowHandler handler = null;
  private WindowHandler() {
    LogManager manager = LogManager.getLogManager();
    String className = this.getClass().getName();
    String level = manager.getProperty(className + ".level");
    setLevel(level != null ? Level.parse(level) : Level.INFO);
    if (window == null)
      window = new LogWindow();
  }
  public static synchronized WindowHandler getInstance() {
    if (handler == null) {
      handler = new WindowHandler();
    }
    return handler;
  }
  public synchronized void publish(LogRecord record) {
    String message = null;
    if (!isLoggable(record))
      return;
    message = getFormatter().format(record);
    window.showInfo(message);
  }
  public void close() {
  }
  public void flush() {
  }
}
public class Main {
  private WindowHandler handler = null;
  private Logger logger = null;
  public Main() {
    handler = WindowHandler.getInstance();
    logger = Logger.getLogger("logging.handler");
    logger.addHandler(handler);
  }
  public void logMessage() {
    logger.info("Hello from ...");
  }
  public static void main(String args[]) {
    Main demo = new Main();
    demo.logMessage();
    WindowHandler h = WindowHandler.getInstance();
    LogRecord r = new LogRecord(Level.WARNING, "The Handler publish method...");
    h.publish(r);
  }
}





Writing Log Records Only After a Condition Occurs

   
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileHandler fhandler = new FileHandler("my.log");
    int numRec = 100;
    MemoryHandler mhandler = new MemoryHandler(fhandler, numRec, Level.SEVERE);
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(mhandler);
  }
}





Writing Log Records to a Log File

   

import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileHandler handler = new FileHandler("my.log");
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(handler);
  }
}





Writing Log Records to Standard Error

   
import java.util.logging.ConsoleHandler;
import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    ConsoleHandler handler = new ConsoleHandler();
    // Add to logger
    Logger logger = Logger.getLogger("com.mycompany");
    logger.addHandler(handler);
  }
}





XMLFormatter based Logging

   
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.XMLFormatter;
public class Main {
  public static void main(String args[]) throws Exception{
    XMLFormatter formatter = new XMLFormatter();
    LogRecord record = new LogRecord(Level.INFO, "XML message..");
    FileHandler handler = new FileHandler("newxml.xml");
    handler.setFormatter(formatter);
    handler.publish(record);
    handler.flush();
  }
}