Java Reference
In-Depth Information
Log4j has different levels defined than the ones used by the built‐in logger. TRACE is the most
detailed level, followed by DEBUG, INFO, WARN, ERROR, and FATAL, which is the least
detailed level. There is also OFF to turn off logging. The methods differ from the built‐in logger as
well. In the previous example, you saw:
logger.log(Level.INFO, "informational message");
With Log4j, you would write:
logger.info("informational message");
To demonstrate the use of Log4j and compare it to the built‐in logger, this next Try It Out repeats
the previous example.
Logging with apache Log4j 2 
try it out
In this exercise, you'll set up logging in a small program using Apache's Log4j 2 logging utility.
1. Download the Apache Log4j 2 from the Apache website.
2. Attach two .jar files to the build path of the project you're working in: log4j-api-2.0.1.jar
and log4j-core-2.0.1.jar .
3. Create a new class called ApacheLogging .
4. Import the logger and LogManager from Log4j and create a new logger object for the class.
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
public class ApacheLogging {
static final Logger log = LogManager.getLogger(ApacheLogging.class.getName());
}
5. Add two methods, main and recalculate , similar to the previous example, but without the log-
ging for now.
public static void main(String[] args) {
int age = 60;
double retirementFund = 10000;
int yearsInRetirement = 20;
String name = "David Johnson";
for (int i = age; i <= 65; i++) {
recalculate(retirementFund, 0.1);
}
double monthlyPension = retirementFund / yearsInRetirement / 12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
if (monthlyPension < 100) {
System.out.println("monthlyPension is too low.");
}
Search WWH ::




Custom Search