Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to set-up log4j

Status
Not open for further replies.

sheed

Programmer
Jun 14, 2005
38
US
I have a jsp/servlet application and I am trying to use log4j for logging purpose. Can someone tell me how can I set-up log4j to work in my application. I have log4j.jar in the path , have custom class to logging i.e.

Code:
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import org.apache.log4j.*;

public class Logging 
{
  private  Logging logr = Logger.getLogger(this.getClass().getName());
  
  public Logging(String name)
  {
      try
      {
          File file = new File(name);
          URL lurl = file.toURL() ;
          PropertyConfigurator.configure(lurl);          
      }
      catch (Exception ex)
      {
          
      }
  }

  public void debug (String msg)
  {
     logger.debug(  msg );
  }

 ..................................


But I can't figure out where and how I instantiate this class,
and where should I put log4j.properties file so I can read it and pass it to this custom class and start the logging. Any help is appreciated.

Thanks
 
You should declare loggers at the top of classes you want to generate logging from
Code:
import org.apache.log4j.Logger;

public class MyClassForSomething {
  private static Logging LOGGER = Logger.getLogger(MyClassForSomething.class);

  //...an example method
  public void doSomething(){

    // ... an INFO log entry
    LOGGER.info("We are now doing something.");

    // ... a DEBUG log entry
    LOGGER.debug("Loop entered");

    try {
       //...some code
    } catch ( SomeException ex ){
      LOGGER.error("Oh dear, it's broken", ex);
    }
  }
}

You can control which packages in your program are activated for logging, and at which logging level, and where and in which format they end up, all from the log4j.properties (or log4j.xml) file outside your program.

Incidentally, there is a forum specially for log4j. forum949.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top