Java/Language Basics/Log4j

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

Содержание

and assign level and appender to your own logger

  
log4j.logger.ru.foo=DEBUG,FILE





define a named logger

  
log4j.logger.dataAccessLogger = com.apress.logging.logger





define the appender named CONSOLE

  
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.conversionPattern=%m%n





define the appender named FILE

  
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${user.home}/log.out





define the root logger with two appenders writing to console and file

  
log4j.rootLogger = DEBUG, CONSOLE, FILE





define your own logger named com.foo

Example log4j Configuration File

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
//Example log4j Configuration File 
/*
#set the level of the root logger to DEBUG and set its appender
as an appender named X
log4j.rootLogger = DEBUG, X
#set the appender named X to be a console appender
log4j.appender.X=org.apache.log4j.ConsoleAppender
#set the layout for the appender X
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.conversionPattern=%m%n
*/
// Complex log4j Configuration File
/*
# define the root logger with two appenders writing to console and file
log4j.rootLogger = DEBUG, CONSOLE, FILE
#define your own logger named com.foo
log4j.logger.ru.foo=com.foo.MyLogger
#assign appender to your own logger
log4j.logger.ru.foo.appender=FILE
#define the appender named
FILE log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${user.home}/log.out
#define the appender named CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.conversionPattern=%m%n
log4j.properties

#set the level of the root logger to DEBUG (the lowest level) and
set its appender
#as an appender named X
log4j.rootLogger = DEBUG, X
#set your own logger
log4j.logger.ru.apress.logging.log4j=DEBUG, X
#set the appender named X to be a console appender
log4j.appender.X=org.apache.log4j.ConsoleAppender
#set the layout for the appender X
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.conversionPattern=%p-%m%n
*/





html.properties: configuring the custom logger

  
log4j.logger.ru.apress.logging.log4j=DEBUG, FILE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=htmlLayout.html
log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.Title=HTML Layout Demo
log4j.appender.FILE.layout.LocationInfo=true





jdbc.properties configuration file for log4j

  
#configuring the custom logger
log4j.logger.ru.apress.logging.log4j=DEBUG, DB
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DB.URL=jdbc:odbc:dbdef
log4j.appender.DB.user=system
log4j.appender.DB.password=manager
log4j.appender.DB.sql=INSERT INTO LOGGING_DATA VALUES("%x","%d{yyyy-MM-dd}","%C","%p","%m")





jms.properties configuration file for JMS

  
#configuring the custom logger
log4j.logger.ru.apress.logging.log4j=DEBUG, JMS
#configuring the JMS appender
log4j.appender.JMS=org.apache.log4j.net.JMSAppender
log4j.appender.JMS.topicConnectionFactoryBindingName=TopicConnectionFactory
log4j.appender.JMS.topicBindingName=loggingTopic





log4j: A complete example

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
import org.apache.log4j.or.ObjectRenderer;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;
class CustomerOrder {
  /** Holds value of property productName. */
  private String productName;
  /** Holds value of property productCode. */
  private int productCode;
  /** Holds value of property productPrice. */
  private int productPrice;
  /** Creates a new instance of CustomerOrder */
  public CustomerOrder() {
  }
  public CustomerOrder(String name, int code, int price) {
    this.productCode = code;
    this.productPrice = price;
    this.productName = name;
  }
  /**
   * Getter for property productName.
   * 
   * @return Value of property productName.
   */
  public String getProductName() {
    return this.productName;
  }
  /**
   * Setter for property productName.
   * 
   * @param productName
   *            New value of property productName.
   */
  public void setProductName(String productName) {
    this.productName = productName;
  }
  /**
   * Getter for property productCode.
   * 
   * @return Value of property productCode.
   */
  public int getProductCode() {
    return this.productCode;
  }
  /**
   * Setter for property productCode.
   * 
   * @param productCode
   *            New value of property productCode.
   */
  public void setProductCode(int productCode) {
    this.productCode = productCode;
  }
  /**
   * Getter for property productPrice.
   * 
   * @return Value of property productPrice.
   */
  public int getProductPrice() {
    return this.productPrice;
  }
  /**
   * Setter for property productPrice.
   * 
   * @param productPrice
   *            New value of property productPrice.
   */
  public void setProductPrice(int productPrice) {
    this.productPrice = productPrice;
  }
}
class ProductFilter extends Filter {
  /** Creates a new instance of ProductFilter */
  public ProductFilter() {
  }
  public int decide(LoggingEvent event) {
    int result = this.ACCEPT;
    //obtaining the message object passed through Logger
    Object message = event.getMessage();
    //checking if the message object is of correct type
    if (message instanceof CustomerOrder) {
      CustomerOrder order = (CustomerOrder) message;
      int productCode = order.getProductCode();
      //checking for the product code greater than 100 only
      if (productCode < 100) {
        result = this.DENY;
      }
    } else {
      //this filter can ignore this, pass to next filter
      result = this.NEUTRAL;
    }
    return result;
  }
}
class OrderRenderer implements ObjectRenderer {
  private static final String separator = "-";
  /** Creates a new instance of OrderRenderer */
  public OrderRenderer() {
  }
  public String doRender(Object obj) {
    StringBuffer buffer = new StringBuffer(50);
    CustomerOrder order = null;
    String productName = null;
    int productCode = 0;
    int productPrice = 0;
    //check if the instance is of correct type CustomerOrder
    if (obj instanceof CustomerOrder) {
      order = (CustomerOrder) obj;
      productName = order.getProductName();
      productCode = order.getProductCode();
      productPrice = order.getProductPrice();
      buffer.append(productName);
      buffer.append(separator);
      buffer.append(new Integer(productCode).toString());
      buffer.append(separator);
      buffer.append(new Integer(productPrice).toString());
    }
    return buffer.toString();
  }
}
public class ProductFilterDemo {
  private static Logger logger = Logger.getLogger("name");
  /** Creates a new instance of ProductFilterDemo */
  public ProductFilterDemo() {
  }
  public void processOrder(CustomerOrder order) {
    logger.info(order);
  }
  public static void main(String args[]) {
    CustomerOrder order1 = new CustomerOrder("Beer", 101, 20);
    CustomerOrder order2 = new CustomerOrder("Lemonade", 95, 10);
    CustomerOrder order3 = new CustomerOrder("Chocolate", 223, 5);
    ProductFilterDemo demo = new ProductFilterDemo();
    demo.processOrder(order1);
    demo.processOrder(order2);
    demo.processOrder(order3);
  }
}
//filter_properties.xml
/*
 * 
 * <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM
 * "log4j.dtd">
 * 
 * <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 * 
 * <renderer renderedClass="com.apress.business.CustomerOrder"
 * renderingClass="com.apress.logging.log4j.renderer.OrderRenderer"> </renderer>
 * 
 * <appender name="A1" class="org.apache.log4j.ConsoleAppender">
 * 
 * <layout class="org.apache.log4j.PatternLayout"> <param
 * name="ConversionPattern" value="%t %-5p %c{2} - %m%n"/> </layout> <filter
 * class="com.apress.logging.log4j.filter.ProductFilter"/> </appender>
 * 
 * <logger name="com.apress.logging.log4j"> <level value="debug"/> <appender-ref
 * ref="A1"/> </logger> </log4j:configuration>
 */





log4j: advanced log

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/

import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
public class AdvancedLogging {
  private static Logger logger = Logger.getLogger("name");
  private String userName = null;
  private double balance;
  /** Creates a new instance of AdvancedLogging */
  public AdvancedLogging(String user) {
    this.userName = user;
  }
  /**
   * Deposit some amount
   */
  public void deposit(double amount) {
    NDC.push(userName);
    balance += amount;
    logger.info("Deposited " + amount + " new balance: " + balance);
    NDC.pop();
  }
  /**
   * withdraw some amount
   */
  public void withdraw(double amount) {
    NDC.push(userName);
    if (balance >= amount) {
      balance -= amount;
      logger.info("Withdrawn " + amount + " new balance: " + balance);
    } else {
      System.out.println("Not enough balance");
      logger.error("Failed to withdraw: balance: " + balance
          + " attempted withdraw: " + amount);
    }
    NDC.pop();
  }
  public static void main(String args[]) {
    AdvancedLogging demo = new AdvancedLogging("sam");
    demo.deposit(100.50);
    demo.withdraw(80);
    demo.withdraw(50);
  }
}





log4j: asynchronous log

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/

import org.apache.log4j.AsyncAppender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Logger;
public class AsyncLogging {
  private static Logger logger = Logger.getLogger("name");
  private AsyncAppender asyncAppender = null;
  private ConsoleAppender consoleAppender = null;
  /** Creates a new instance of AsyncLogging */
  public AsyncLogging() {
    try {
      logger.setAdditivity(false);
      asyncAppender = (AsyncAppender) logger.getRootLogger().getAppender(
          "ASYNC");
      asyncAppender.setBufferSize(4);
    } catch (Exception e) {
      System.out.println("error: " + e.toString());
    }
  }
  /**
   * This method simply logs the messages
   */
  public void doLogging() {
    logger.debug("Hello 1");
    logger.debug("Hello 2");
    logger.debug("Hello 3");
    //logger.debug("Hello 4");
    //logger.debug("Hello 5");
  }
  /**
   * the main method
   */
  public static void main(String args[]) {
    AsyncLogging demo = new AsyncLogging();
    demo.doLogging();
  }
}





log4j config file: configuring the appender CONSOLE

  
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.TTCCLayout





log4j config file: configuring the layout TTCCLayout

  
log4j.appender.CONSOLE.layout.ThreadPrinting=false
og4j.appender.CONSOLE.layout.ContextPrinting=false
log4j.appender.CONSOLE.layout.CategoryPrefixing=false
log4j.appender.CONSOLE.layout.DateFormat=RELATIVE





log4j config file: configuring the named logger

  
log4j.logger.ru.apress.logging.log4j=DEBUG, CONSOLE





log4j config file: configuring the root logger

  
log4j.rootLogger=DEBUG, CONSOLE





log4j Configuration File: assign appender to your own logger

  
log4j.logger.ru.foo.appender=FILE





log4j Configuration File: define the appender named

  
FILE log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${user.home}/log.out





log4j Configuration File: define the appender named CONSOLE

  
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.conversionPattern=%m%n





log4j Configuration File: define the root logger with two appenders writing to console and file

  
log4j.rootLogger = DEBUG, CONSOLE, FILE





log4j Configuration File: define your own logger named com.foo

  
log4j.logger.ru.foo=com.foo.MyLogger





log4j Configuration File: set the appender named X to be a console appender

  
log4j.appender.X=org.apache.log4j.ConsoleAppender





log4j Configuration File: set the layout for the appender X

  
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.conversionPattern=%m%n





log4j Configuration File: #set the level of the root logger to DEBUG and set its appender as an appender named X

  
log4j.rootLogger = DEBUG, X





log4j: File Based Logg Demo

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
import org.apache.log4j.*;
public class FileBasedLoggingDemo implements Runnable {
  private static Logger logger = Logger.getLogger("filename");
  /** Creates a new instance of FileBasedLoggingDemo */
  public FileBasedLoggingDemo() {
  }
  /**
   * This method is called by the application. This method creates a new
   * thread to start logging
   */
  public void doLogging() {
    Thread t = new Thread(this);
    t.start();
  }
  /**
   * The thread"s run() method, which does repeated logging at an interval of
   * 60secs.
   */
  public void run() {
    int count = 1;
    while (true) {
      //logging information
      try {
        logger.debug("Logging the information..." + count);
        Thread.sleep(60 * 1000);
        count++;
      } catch (Exception e) {
        logger.warn("Exception occured", e);
      }
    }
  }
  /**
   * the main method
   */
  public static void main(String args[]) {
    FileBasedLoggingDemo demo = new FileBasedLoggingDemo();
    demo.doLogging();
  }
}





log4j: layout demo

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
import org.apache.log4j.Logger;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.TTCCLayout;
import org.apache.log4j.NDC;
public class LayoutDemo {
  private static Logger logger = Logger.getLogger("name");
  private ConsoleAppender appender = null;
  private TTCCLayout layout = null;
  /** Creates a new instance of LayoutDemo */
  public LayoutDemo() {
    //set the parent additivity to false
    logger.setAdditivity(false);
    //initialize the layout
    layout = new TTCCLayout("yyyy-MM-dd");
    //initialize the console appender with the layout
    appender = new ConsoleAppender(layout, "System.out");
    //adding the console appender to the logger
    logger.addAppender(appender);
  }
  public void computeSquareRoot(double number) {
    NDC.push(new Double(number).toString());
    double sqrt = Math.sqrt(number);
    logger.info("The sqrt value: " + sqrt);
    NDC.pop();
  }
  public static void main(String args[]) {
    LayoutDemo demo = new LayoutDemo();
    demo.ruputeSquareRoot(22);
    demo.ruputeSquareRoot(44);
  }
}





log4j: log and servlet

  
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;
import org.apache.log4j.*;
public class LoggingServlet extends HttpServlet {
    private static Logger logger =Logger.getLogger(LoggingServlet.class);
    public void doPost(HttpServletRequest req, HttpServletResponse res)
                       throws IOException, ServletException
    {
        logger.info("invoked the LoggingServlet...");
        PrintWriter writer = res.getWriter();
        writer.println("Check your web server console...");
        writer.flush();
        writer.close();
    }
}





log4j.properties: daily layout

  
log4j.appender.DAILY.layout=org.apache.log4j.PatternLayout
log4j.appender.DAILY.layout.conversionPattern=%p - %m%n





log4j.properties: file layout

  
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%p - %m%n





log4j.properties: rolling layout

  
log4j.appender.ROLLING.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING.layout.conversionPattern=%p - %m%n





log4j.properties: set the appender CONSOLE

  
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender





log4j.properties: set the appender DAILY

  
log4j.appender.DAILY=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DAILY.File=${user.home}/daily.log
log4j.appender.DAILY.DatePattern="." yyyy-MM-dd-HH-mm





log4j.properties: set the appender FILE

  
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${user.home}/out.log





log4j.properties: set the appender ROLLING

  
log4j.appender.ROLLING=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING.File=${user.home}/rolling.log
log4j.appender.ROLLING.MaxFileSize=1KB





log4j.properties: set the layout for the appenders

  
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.conversionPattern=%p - %m%n





log4j.properties: set the level of the root logger to DEBUG (the lowest level) and set its appenders named DEBUG and CONSOLE

  
log4j.rootLogger = DEBUG, CONSOLE





log4j.properties: set your own logger

  
log4j.logger.ru.apress.logging.log4j=DEBUG, FILE, ROLLING, DAILY





log4j: simple log

  
/*
Logging In Java with the JDK 1.4 Logging API and Apache log4j
by Samudra Gupta    
Apress Copyright 2003 
ISBN:1590590996
*/
import org.apache.log4j.Logger;
public class SimpleLogging {
    /** Creates a new instance of SimpleLogging */
    public SimpleLogging() {
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Logger logger =Logger.getLogger("name");
        logger.info("Hello this is an info message");
    }
}





Logging Servlet with log4j

  
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;
import org.apache.log4j.*;
public class LoggingServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(LoggingServlet.class);
    public void doPost(HttpServletRequest req, HttpServletResponse res)
                       throws IOException, ServletException
    {
        logger.info("invoked the LoggingServlet...");
        PrintWriter writer = res.getWriter();
        writer.println("Check your web server console...");
        writer.flush();
        writer.close();
    }
}





nt.properties for NT configuration

  
#configuring the custom logger
log4j.logger.ru.apress.logging.log4j=DEBUG, NT
#configuring the NT appender
log4j.appender.NT=org.apache.log4j.nt.NTEventLogAppender
log4j.appender.NT.layout=org.apache.log4j.SimpleLayout





Pass the configuration file and configuration class

  
java -Dlog4j.configuration=config file yourApp
java -Dlog4j.configurationClass=config class yourApp





set the appender named testAppender to be a console appender

  
log4j.appender.testAppender=org.apache.log4j.ConsoleAppender





set the layout for the appender testAppender

  
log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.testAppender.layout.conversionPattern=%m%n





set the level of the root logger to DEBUG and set its appender as an appender named testAppender

  
log4j.rootLogger = DEBUG, testAppender





smtp.properties for EMail based logging

  
#configuring the custom logger
log4j.logger.ru.apress.logging.log4j=DEBUG, SMTP
#configuring the SMTP appender
log4j.appender.SMTP=org.apache.log4j.net.SMTPAppender
log4j.appender.SMTP.SMTPHost=smtp.mail.yahoo.ru
log4j.appender.SMTP.to=clientname@mailserver.ru
log4j.appender.SMTP.subject=Testing the appender
log4j.appender.SMTP.from=yourname@mailserver.ru
log4j.appender.SMTP.layout=org.apache.log4j.SimpleLayout





xml.properties: configuring the custom logger

  
log4j.logger.ru.apress.logging.log4j=DEBUG, FILE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=xmlLayout.xml
log4j.appender.FILE.layout=org.apache.log4j.xml.XMLLayout
log4j.appender.FILE.layout.LocationInfo=true