Log4j is java logging framework which is fast, reliable and flexible. It is open source and free. You can click here to go to it’s home page.
You can configure it by configuration file. In that file, you can configure logging levels, log information layout. You can also configure where the log data saved to, such as console, file and database etc.
1. log4j Components.
There are three components in Log4j.
- logger : In charge of catching logging data.
- layouts : In charge of format logging data in various styles.
- appenders : In charge of writing logging data to numerous chosen locations.
2. log4j Features.
- Use named logger hierarchy.
- Thread safe.
- Faster than other logger library.
- Can assign multiple appender to one logger.
- Supports internationalization.
- Can use configuration file to change logging behavior at runtime.
- Can process Java Exceptions.
- There are totally 7 log levels, they are ALL, DEBUG, TRACE, INFO, WARN, FATAL and ERROR.
- The log data format can be adjusted by customize Layout class.
- You can easily change log output destination and log writing strategy by implement Appender interface.
3. log4j – Download.
- Go to log4j download page, get the latest version.
- Unzip the zip file to local directory such as
4. Add log4j To System Environment Variable Path and ClassPath.
- For Windows.
1.1. Right click computer, click Properties in popup menu.
1.2. In the popup window, click “Advanced system settings —> Environment Variables —> Path”, add your log4j directory path to the value. The Path value after changed for my environment should be
1.3. Add log4j-api-2.8.2.jar to ClassPath system environment variable like above.
- For Linux.
$ export CLASSPATH=$CLASSPATH:/usr/local/apache-log4j-2.8.2-bin/log4j-api-2.8.2.jar $ export PATH=$PATH:/usr/local/apache-log4j-2.8.2-bin/
5. Add log4j Jar In Java Project.
- Right click your java project name, click ” Build Path —> Configure Build Path”.
- Click ” Add External JARs ” button to choose log4j-api-2.8.2.jar from your unzipped folder. Click OK to close the dialog.