Log4j is a java logging framework that is fast, reliable, and flexible. It is open-source and free. You can click here to go to it’s official home page.
You can configure it with a 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, 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.
- Faster than other logger libraries.
- Can assign multiple appenders to one logger.
- Supports internationalization.
- Can use a configuration file to change logging behavior at runtime.
- Can process Java Exceptions.
- There is a total of 7 log levels, they are ALL, DEBUG, TRACE, INFO, WARN, FATAL and ERROR.
- The log data format can be adjusted by customizing the Layout class.
- You can easily change the log output destination and log writing strategy by implement the Appender interface.
3. log4j – Download.
- Go to the log4j download page, get the latest version.
- Unzip the zip file to a local directory such as
4. Add log4j To System Environment Variable Path and ClassPath.
- For Windows, you can follow the below steps.
- Right-click your PC icon in windows explorer, click Properties in the popup menu.
- 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 is
- Add log4j-api-2.8.2.jar to the ClassPath system environment variable like above.
- For Linux, you can run the below command in a terminal.
$ 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 the Properties menu item to open the java project Properties dialog window.
- Click the ” Java Build Path ” on the left and then click the Libraries tab on the right side.
- Click the ” Add External JARs ” button to choose log4j-api-2.8.2.jar from your unzipped folder. Click OK to close the dialog.