Hi,
I am trying to configure the logger in java to log my messages. I have downloaded and added the log4j.jar to my classpath. I am receving two error messages while I am running the program to check it.The code I am using is :

import org.apache.log4j.*;

public class LoggerClass{
public static Logger myLogger =
           Logger.getLogger(LoggerClass.class.getName( ));
    Appender myAppender;
    SimpleLayout myLayout;

public LoggerClass(){ 

    myLayout = new SimpleLayout();
    myAppender = new ConsoleAppender(myLayout);

}
public static void main(String args[])
{
 myLogger.info("This is info");
 myLogger.error("Error");
 myLogger.debug("Debug");
}
}

I am receiving the following error messages while trying to run the program :

log4j:WARN No appenders could be found for logger (LoggerClass).
log4j:WARN Please initialize the log4j system properly.

What could be the cause...help would be greatly appreciated?

Recommended Answers

All 3 Replies

I found these tips for "Logging for Apache Tomcat and Velocity using Log4j"
I never used this Log4j, but looks like internet is full of similar questions, so it will be up to you find an answer or maybe later somebody can help. However you can start with this google search results

PS: In the future please use code tags to insert any code into post. It is that hash sign "#" in thread toolbar and your code goes between them. Thank you

Try adding the following to your constructor:

public LoggerClass(){ 
           BasicConfigurator.configure();

  myLayout = new SimpleLayout();
  myAppender = new ConsoleAppender(myLayout);

  myLogger.addAppender( myAppender );
    
}

If you want a file appender, you can add one of those like this

try{
    RollingFileAppender fileAppender = new RollingFileAppender(new PatternLayout("%d: %m:  %l " + System.getProperty("line.separator") ), System.getProperty("user.dir") + java.io.File.separator +"application.log");  // can change the pattern and file location to whatever you need
    fileAppender.setMaxBackupIndex(1);
    fileAppender.setMaximumFileSize(1000000L);
    fileAppender.setThreshold(Priority.WARN); // if you want to set a threshold.
    myLogger.addAppender(fileAppender);
    myLogger.info("Started Rolling File Appender");

} catch (Exception ex){
  /* whatever you need here */
}

Or do the smart thing, and supply a configuration file for log4j as explained in the manual.
Far more flexible, and you can tune logging options without needing to recompile everything.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.