Saturday, April 18, 2009

Using Log4J in Netbeans 6.5 for Java (Beginners)

Took me 3 frustrating nights to actually get it right and working the way I want it to. I'm no pro but I'll cover as much as possible so anyone coding in Java with Netbeans that wishes to use Log4J does not have to go through countless sites just to get something so simple correct.

Checklist;
1) JDK is installed. (download the one under 'Java SE Development Kit (JDK)'). Of course you can choose the bundled ones but I just old fashion, prefer to download it seperately.
2) Netbeans installed. (go for the full one. heck i know but bigger is better)
3) download Log4J. Extract just the log4j-1.2.15.jar (this is the version I am using so it might differ after time) to 'C:\Program Files\Java\jdk1.6.0_12\jre\lib\ext' (this is where I installed my jdk). For me I renamed it to log4j.jar before copying it to that folder.
4) Check if Log4J is in Netbeans Library. If not then go to 'tools' ->'Libraries'.






With that out of the way.. if you first studied log4j from this site 'Don't Use System.out.println' like me, there are a few problem to be encountered;

For one, it doesn't work with Netbeans (don't worry, I'll cover it soon). Besides that, it throws a warning message everytime it is compiled; 'uses or overrides a deprecated API'. To overcome this, replace the use of 'Category' with 'Logger' (more on that later).


Modified main class from 'Don't Use System.out.println', this is my 'Main.java' for package 'testlogging';

package testlogging;
import org.apache.log4j.*;

public class Main {

// Initialize a logging category. Here, we get THE ROOT CATEGORY
//static Category cat = Category.getRoot();
// Or, get a custom category
//static Category cat = Category.getInstance(Main.class.getName());
static Logger cat = Logger.getLogger(Main.class.getName());

// From here on, log away! Methods are: cat.debug(your_message_string),
// cat.info(...), cat.warn(...), cat.error(...), cat.fatal(...)

public static void main(String args[]) {
BasicConfigurator.configure();

// Try a few logging methods
cat.debug("Start of main()");
cat.info("Just testing a log message with priority set to INFO");
cat.warn("Just testing a log message with priority set to WARN");
cat.error("Just testing a log message with priority set to ERROR");
cat.fatal("Just testing a log message with priority set to FATAL");

// Alternate but INCONVENIENT form
//cat.log(Priority.DEBUG, "Calling init()");
cat.debug("Calling init()");

new Main().init();
}

public void init() {
java.util.Properties prop = System.getProperties();
java.util.Enumeration enum1 = prop.propertyNames();

cat.info("***System Environment As Seen By Java***");
cat.debug("***Format: PROPERTY = VALUE***");

while (enum1.hasMoreElements()) {
String key = (String) enum1.nextElement();
cat.info(key + " = " + System.getProperty(key));
}
}
}

The log4j.properties for it modified;


#### Use two appenders, one to log to console, another to log to a file
# log4j.rootCategory=debug, stdout, R
log4j.rootLogger=debug, stdout, R

# Print only messages of priority WARN or higher for your category
# log4j.category.your.category.name=WARN
# Specifically inherit the priority level
#log4j.category.your.category.name=INHERITED

# Print only messages of level WARN or above in the package
log4j.logger.testlogging=DEBUG


#### First appender writes to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

#### Second appender writes to a file
#log4j.appender.R=org.apache.log4j.FileAppender
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log

# Control the maximum log file size
log4j.appender.R.MaxFileSize=100KB
# Archive log files (one backup file here)
log4j.appender.R.MaxBackupIndex=1

# Truncate 'test' if it aleady exists.
#log4j.appender.R.Append=false

log4j.appender.R.layout=org.apache.log4j.PatternLayout
# log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
log4j.appender.R.layout.ConversionPattern=%n%p - %m


From all notes and tutorial, log4j.properties is being advised to put together with the class files. If you get;

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

This means that log4j.properties is not detected. Close Netbeans. Then go to your class folder (for me is 'D:\MyJava\TestLogging\src\testlogging'). Move log4j.properties from that folder and put it under 'D:\MyJava\TestLogging\src'. Meaning to say to put it one directory back. Open Netbeans and you'll see something like this;




Make sure log4j.properties is under ''. If not, check if you have it under the correct place. So far Netbeans never fail to update it for me.

Note: try to read 'log4j -> Documentation -> Introduction' It really helps alot.


.
.
..
...

All the best, and I don't wanna blog about coding anymore... takes soooo much work!! @.@""

.....

6 comments:

David said...

Hi,
Where can i find the actual log file the program is writing?

JarvisjerK said...

Assuming that you have it running correctly, then the log file should be in the same folder as where your program resides.

felice said...

I can't take you enough!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! :):):)

JarvisjerK said...

My Pleasure~! (=

Anonymous said...

thanks! you really helped me out with this post. I was starting to go crazy with netbeans & log4j not working together.

ashok venna said...

HI Friend,

I am deploying my project in the server and I'm trying to use Log4j in my project. In which folder do you suggest to save the log files/messages in our project folder.